常见图表
由上一篇博客我们可以大致了解,常见的图表分为以下几种:
- 折线图:以折线方式反应数据变化趋势
- 直方图:利用方块大小反应数据差异
- 条形图:显示各个项目之间的比较情况,和直方图有类似的作用
- 饼图:显示各数据的百分比情况
- 散点图:显示若干数据系列中各数值之间的关系
- 箱型图:用来显示一组数据分散情况的统计图,在识别异常值方面有一定的优越性
基础图标函数 | 描述 |
---|---|
plt.plot() | 坐标图 |
plt.boxplot() | 箱型图 |
plt.bar() | 条形图 |
plt.barh() | 横向条形图 |
plt.polar() | 极坐标图 |
plt.pie() | 饼图 |
plt.cohere() | X-Y的相关性函数 |
plt.scatter() | 散点图,x,y长度相同 |
plt.step() | 步阶图 |
plt.hist() | 直方图 |
plt.contour() | 等值图 |
plt.vlines() | 垂直图 |
plt.plot_date() | 绘制数据日期 |
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
条形图
条形图
# 条形图
labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 34, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]
# 标签位置
x = np.arange(len(labels))
# 设置条形宽度
height = 0.35
fig, ax = plt.subplots()# 设置子绘图区域
rects1 = ax.bar(x - height/2, men_means, height, label='Men')
rects2 = ax.bar(x + height/2, women_means, height, label='Women')
ax.set_xlabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
plt.show()
# 水平条形图
y = np.arange(len(labels))
fig, ax = plt.subplots()
rects1 = ax.barh(y - height/2, men_means, height, label='Men')
rects2 = ax.barh(y + height/2, women_means, height, label='Women')
ax.set_xlabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_yticks(y)
ax.set_yticklabels(labels)
ax.legend()
plt.show()
折线图
# 设置字体为黑体
matplotlib.rcParams['font.family']='SimHei'
x = [1,2,3,4,5]
y = [10,12,23,44,65]
# ms表示星型标记字符的大小
plt.plot(x,y,'r*--',ms=10,label="a")
plt.xlabel("发布时间")
plt.ylabel("访问量")
plt.title("翠花博客活跃度")
plt.legend()
plt.show()
饼图
labels= 'Frogs','Hogs','Dogs','Logs'
sizes = [15,30,45,10]
explode = (0,0.1,0,0)
plt.pie(sizes,explode=explode,labels=labels,autopct='%1.1f%%',shadow=False,startangle=90)
plt.show()
pie参数 | 描述 |
---|---|
sizes | 约定饼图尺寸 |
explode | 指出哪块突出 |
labels | 表示那块标签 |
autopct | 表示中间显示百分比的方式 |
shadow | 表示是否带有阴影 |
startangle | 表示饼图起始角度 |
直方图
# 生成高斯分布的概率密度随机数 50为均值 20为标准差
a = np.random.normal(50,20,size=100)
plt.xlabel('横轴:time',fontproperties='SimHei',fontsize=20)
plt.ylabel('纵轴:Hz',fontproperties='Kaiti',fontsize=10)
plt.hist(a,20,histtype='stepfilled',facecolor='b',alpha=0.75)
plt.show()
散点图
fig,ax=plt.subplots() # fig ax分别图表和图表绘制的区域
# 横轴和纵轴分别对应正态分布10倍后的点,标记方式为o型
ax.plot(10*np.random.randn(100),10*np.random.randn(100),'o')
ax.set_title('Simple Scatter')
plt.show()