首页 > 编程语言 >Python_matplotlib进阶

Python_matplotlib进阶

时间:2024-04-03 23:58:39浏览次数:17  
标签:plt 进阶 title Python matplotlib df sns pd import

Python_matplotlib 跳转链接


之前的博客中已经展示了使用python的matplotlib库进行一些基础图像的绘制,本篇进一步展示一些matplotlib中的一些进阶图像绘制。

import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
Titanic = pd.read_csv("/Users/guxiang/应用统计/统计学基础/(02)习题数据/exercise/chap02/exercise2_1.csv", encoding='gbk')
print(Titanic.head())

在这里插入图片描述

# 条形图
t1 = pd.crosstab(Titanic.Sex, Titanic.Survived)
t1.plot(kind='bar')
plt.title('(a)垂直并列条形图')
plt.show()

在这里插入图片描述

t1.plot(kind='barh')
plt.title('(b)水平并列条形图')
plt.show()

在这里插入图片描述

t2 = pd.crosstab(Titanic.Sex, Titanic.Survived)
t2.plot(kind='bar', stacked=True)
plt.title('(c)垂直堆叠条形图')
plt.show()

在这里插入图片描述

t2 = pd.crosstab(Titanic.Sex, Titanic.Survived)
t2.plot(kind='barh', stacked=True)
plt.title('(d)水平堆叠条形图')
plt.show()

在这里插入图片描述

# 计算舱位类别分布
class_counts = Titanic['Class'].value_counts().sort_index()  # 按照舱位等级进行排序

# 创建饼图
plt.figure(figsize=(6, 6))
plt.pie(class_counts, labels=class_counts.index, autopct='%1.1f%%', startangle=90)
plt.title('Titanic乘客舱位类别分布')
plt.axis('equal')  # 使饼图成为一个正圆
plt.show()

在这里插入图片描述

# 创建环形图
plt.figure(figsize=(6, 6))
plt.pie(class_counts, labels=class_counts.index, autopct='%1.1f%%', startangle=90, wedgeprops=dict(width=0.4))
plt.title('Titanic乘客舱位类别分布')
plt.axis('equal')  # 使环形图成为一个正圆
plt.show()

在这里插入图片描述

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
plt.rcParams['font.sans-serif'] = ['SimHei']
faithful = pd.read_csv("/Users/guxiang/应用统计/统计学基础/(02)习题数据/exercise/chap02/exercise2_2.csv", encoding='gbk')
print(faithful.head())

在这里插入图片描述

# 直方图
sns.histplot(faithful.eruptions)
plt.title('(a)默认绘制(y轴为频数)')
plt.show()

# 核密度曲线
sns.histplot(faithful.eruptions, kde=True)
plt.title('(b)核密度曲线(y轴为频率)')
plt.show()

在这里插入图片描述
在这里插入图片描述

# 核密度比较曲线
plt.figure(figsize=(8, 6))
sns.kdeplot(faithful['eruptions'], label='Eruptions', fill=True)
sns.kdeplot(faithful['waiting'], label='Waiting', fill=True)

plt.title('核密度比较曲线')
plt.xlabel('Value')
plt.ylabel('Density')
plt.legend()
plt.show()

在这里插入图片描述

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
plt.rcParams['font.sans-serif'] = ['SimHei']
mtcars = pd.read_csv("/Users/guxiang/应用统计/统计学基础/(02)习题数据/exercise/chap02/exercise2_3.csv", encoding='gbk')
print(mtcars.head())

在这里插入图片描述

# 绘制散点图
plt.figure(figsize=(8, 6))
plt.scatter(mtcars['wt'], mtcars['mpg'], c='blue', alpha=0.6)
plt.xlabel('Car Weight (wt)')
plt.ylabel('Miles per Gallon (mpg)')
plt.title('散点图')
plt.grid(True)
plt.show()

在这里插入图片描述

# 绘制散点图矩阵
sns.set(style="ticks")
sns.pairplot(mtcars)
plt.show()

在这里插入图片描述

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
plt.rcParams['font.sans-serif'] = ['SimHei']
iris = pd.read_csv("/Users/guxiang/应用统计/统计学基础/(02)习题数据/exercise/chap02/exercise2_4.csv", encoding='gbk')
print(iris.head())

在这里插入图片描述

# 折线图
iris_50 = iris.head(50)
dfs = [iris_50['Sepal.Length'], iris_50['Sepal.Width'], iris_50['Petal.Length'], iris_50['Petal.Width']]
sns.lineplot(data=dfs, markers=True)

在这里插入图片描述

# 雷达图
import numpy as np
datalenth = 50
df1 = np.array(iris_50['Sepal.Length'])
df2 = np.array(iris_50['Sepal.Width'])
df3 = np.array(iris_50['Petal.Length'])
df4 = np.array(iris_50['Petal.Width'])

angles = np.linspace(0, 2*np.pi, datalenth, endpoint=False)
df1 = np.concatenate((df1, [df1[0]]))
df2 = np.concatenate((df2, [df2[0]]))
df3 = np.concatenate((df3, [df3[0]]))
df4 = np.concatenate((df4, [df4[0]]))
angles = np.concatenate((angles, [angles[0]]))

plt.figure(figsize=(6, 6), facecolor='lightyellow')
plt.polar(angles, df1, 'r--', linewidth=1, label='Sepal.Length')
plt.polar(angles, df2, 'b', linewidth=1, label='Sepal.Width')
plt.polar(angles, df3, 'k', linewidth=1, label='Petal.Length')
plt.polar(angles, df4, 'g', linewidth=1, label='Petal.Width')
 
plt.show()

在这里插入图片描述

# 一些图像操作
import numpy as np
fit = np.poly1d(np.polyfit(x, y, deg=1)) # 使用一项式拟合
y_hat = fit(x)

plt.plot(x.mean(), y.mean(), 'ro', markersize=20, fillstyle='bottom') # 添加均值点并设置点的大小,颜色和填充类型
plt.axhline(y.mean(), color='black', ls='--', lw=1)
plt.axvline(x.mean(), color='black', ls=(0,(5,10)), lw=1)

plt.grid(linestyle=":") # 添加网格线

ax = plt.gca() #得到当前操作图像

# 更改边框颜色
ax.spines['right'].set_color('#4169E1')
ax.spines['left'].set_color('#4169E1')
ax.spines['top'].set_color('royalblue')
ax.spines['bottom'].set_color('b')

plt.show()

在这里插入图片描述

import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ["SimHei"]
df = pd.read_csv("/Users/guxiang/应用统计/统计学基础/(01)例题数据/pydata/chap02/example2_2.csv", encoding='gbk')
print(df)

在这里插入图片描述

plt.subplots(1 ,2, figsize=(10, 6))
# 绘制普通饼图
plt.subplot(121)
pl = plt.pie(df['北京'], labels=df['支出项目'], autopct='%1.2f%%')
plt.title('(a)普通饼图')

plt.subplot(122)
pl = plt.pie(df['北京'], labels=df['支出项目'], shadow=True, autopct='%1.2f%%', explode=(0.2,0,0.1,0,0,0,0,0))

在这里插入图片描述

# 绘制环形图
plt.subplots(1 ,2, figsize=(10, 6))

plt.subplot(121)
p1 = plt.pie(df['北京'], labels=df['支出项目'], autopct='%1.2f%%',
             pctdistance=0.75, wedgeprops={'width':0.5, 'edgecolor':'w'})
plt.title('(a)北京消费支出的环形图')

plt.subplot(122)
colors = ['red', 'yellow', 'slateblue', 'lawngreen', 'magenta', 'green', 'orange', 'cyan', 'pink']
p2 = plt.pie(df['北京'], labels=df['支出项目'], autopct='%1.2f%%', radius=1,
             pctdistance=0.75, colors=colors, wedgeprops={'linewidth':1.8, 'width':0.5, 'edgecolor':'w'})

plt.subplot(122)
colors = ['red', 'yellow', 'slateblue', 'lawngreen', 'magenta', 'green', 'orange', 'cyan', 'pink']
p2 = plt.pie(df['上海'], autopct='%1.2f%%', radius=0.7,
             pctdistance=0.7, colors=colors, wedgeprops={'linewidth':1.8, 'width':0.3, 'edgecolor':'w'})

plt.title('(b)北京和上海消费支出的环形图')

plt.show()

在这里插入图片描述

# 直方图
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
plt.rcParams['font.sans-serif'] = ["SimHei"]
df = pd.read_csv("/Users/guxiang/应用统计/统计学基础/(01)例题数据/pydata/chap02/example2_3.csv", encoding='gbk')

plt.subplots(1, 3, figsize=(16, 5))

plt.subplot(131)
sns.histplot(df['北京'])
plt.title('(a)默认绘制(y轴是频数)')

plt.subplot(132)
sns.histplot(df['上海'], kde=True, stat='frequency')
plt.title('(b)显示核密度曲线(y轴是频率)')

plt.subplot(133)
sns.histplot(df['郑州'], bins=20, kde=True, stat='density')
plt.title('(c)显示核密度曲线(y轴是密度)')

在这里插入图片描述

# 绘制核密度图
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns


plt.rcParams['font.sans-serif'] = ["SimHei"]
plt.rcParams['axes.unicode_minus'] = False

df = pd.read_csv("/Users/guxiang/应用统计/统计学基础/(01)例题数据/pydata/chap02/example2_3.csv", encoding='gbk')

# sns.set_style('darkgrid')可以用来调整风格
plt.subplots(1, 3, figsize=(15, 4))

plt.subplot(131)
sns.kdeplot(df['北京'], bw_adjust=0.2)
plt.title('(a)bw_adjust=0.2')

plt.subplot(132)
sns.kdeplot(df['北京'], bw_adjust=0.5)
plt.title('(b)bw_adjust=0.5')

plt.subplot(133)
sns.kdeplot(df['北京'], bw_method=0.5)
plt.title('(b)bw_method=0.5')

在这里插入图片描述

标签:plt,进阶,title,Python,matplotlib,df,sns,pd,import
From: https://blog.csdn.net/weixin_58607181/article/details/137360353

相关文章

  • 掌握机器学习新星:使用Python和Scikit-Learn进行图像识别
    正文:        随着智能手机和社交媒体的普及,图像数据的生成速度比以往任何时候都快。为了自动化处理这些数据,我们需要强大的图像识别系统。机器学习提供了一种有效的方法来识别和分类图像中的对象。Scikit-Learn是一个流行的Python库,它提供了一系列用于数据挖掘和数据......
  • 计算几何进阶
    二维凸包模板题(luogu.P2742)凸包定义给定二维平面上的点集\(P\),定义能包含这些点的最小凸多边形为\(P\)的凸包。形象地说,凸包就是一根橡皮筋拉伸,使其包括了点集\(P\)中所有点,然后使橡皮筋收紧,橡皮筋就是\(P\)的凸包。例如,下面用红色线段表示了一个点集的凸包(原创图):凸......
  • python常用库(一)
    文章目录python常用库1、math库1.1、常量1.2、数值运算函数1.3、三角函数1.4、双曲函数1.5、其他函数2、datetime库2.1、datetime.date2.2、datetime.time2.3、datetime.datetime2.4、datetime.timedelta2.5datetime.timezone3、itertools库3.1、无限迭代器3.2、对迭......
  • python常用库(二)
    文章目录python常用库4、sys库4.1、**命令行参数**4.2、**模块导入**4.3、**退出程序**4.4、**标准输入输出**4.5、**系统相关信息**4.6、**内存管理**4.7、**其他功能**5、collections库5.1、**Counter计数器**5.2、**defaultdict默认字典**5.3、**OrderedDict有序......
  • 【阿里淘天笔试题汇总】2024-04-03-阿里淘天春招笔试题(第一套)-三语言题解(CPP/Pytho
    ......
  • 【阿里淘天笔试题汇总】2024-04-03-阿里淘天春招笔试题(第二套)-三语言题解(CPP/Pytho
    ......
  • run Python asyncio code in a Jupyter notebook
     NewJupyterlab/notebookimportasyncioimporttimeasyncdefmy_coroutine():awaitasyncio.sleep(1)print("Coroutineexecuted!")s=time.perf_counter()loop=asyncio.get_event_loop()loop.create_task(my_coroutine())asyncio.r......
  • python如何对二维数组排序
    在Python中对二维数组进行排序是一个常见的需求,可以通过多种方式实现。在本博客中,我们将讨论几种常见的方法来对二维数组进行排序。首先,我们可以使用Python的内置函数sorted()对二维数组进行排序。sorted()函数可以接受一个key参数,通过指定key参数来指定排序的方式。下面是......
  • python 如何操作pdf文件
    在Python中操作PDF文件通常涉及以下几个常见的任务:读取PDF内容、创建PDF文件、编辑PDF文件、合并PDF文件、拆分PDF文件等。下面我将介绍如何使用Python中的几个主要库来执行这些操作。读取PDF内容要读取PDF文件的内容,可以使用PyPDF2库。以下是一个简单的示例代码,演示如何......
  • 数据结构与算法分析实验3 [进阶]通过链表实现多项式加法和乘法
    文章目录大致内容介绍多项式加法代码一览头文件Poly.h内容如下:实现文件Poly.cpp内容如下:初始化增加元素删除元素功能函数遍历函数清除销毁打印多项式向多项式内插入一个元素源文件main.cpp内容如下:实现效果:多项式乘法实现方法:在Poly.h中添加声明:在Poly.cpp中添加实现:在......