基本画图操作
内容包括画线、条形图、直方图、饼图。
画线
import matplotlib.pyplot as plt
# r代表红线,默认是实线
plt.plot([0.5*value*value-6 for value in range(0, 10)], 'r')
# go--代表绿色、圆点、虚线
plt.plot([0.2*value*value-6 for value in range(0, 10)], 'go--')
plt.plot([0.8*value*value-3 for value in range(0, 10)], 'y--')
plt.plot([0.7*value*value-6 for value in range(0, 10)], 'bo-.')
plt.show()
output_2_0.png
画条形图
简单条形图
import matplotlib.pyplot as plt
plt.bar(range(1, 10), [0.5*value*value-6 for value in range(1, 10)], alpha=0.8)
plt.show()
output_5_0.png
直方图
统计出现的次数
from matplotlib import pyplot as plt
import numpy as np
a = np.array([77.1, 79.9, 80.9, 90.0, 96, 93, 92.8, 65.8, 80.9, 90.3, 50, 65.3, 66.8, 65.3])
plt.hist(a, bins=range(40, 100, 10), rwidth=0.9)
plt.title("histogram")
plt.show()
output_9_0.png
饼状图
会自动计算出对应的占比
import matplotlib.pyplot as plt
labels = ['Frogs', 'Hogs', 'Dogs', 'Logs']
sizes = [15, 30, 65, 10]
explode = (0, 0, 0.1, 0) # 将占比最大的分离开,着重标注
fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True, startangle=90)
ax1.axis('equal') # 当设置为equal时代表是一个圆
plt.show()
output_11_0.png
设置坐标轴
格式化x和y轴
import matplotlib.pyplot as plt
# 画线
x = range(1, 10)
plt.bar(x, [0.5*value*value-6 for value in range(1, 10)], alpha=0.8)
# 设置y轴百分比
def to_percent(temp, position):
return '%1.0f'%(temp) + '%'
plt.gca().yaxis.set_major_formatter(FuncFormatter(to_percent)) # 格式化y轴刻度
# plt.gca().xaxis.set_major_formatter(FuncFormatter(to_percent)) # 格式化x轴刻度
plt.xticks(x, ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月'], rotation=45)
output_14_1.png
y轴刻度显示在右边
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
fig, ax = plt.subplots()
ax.plot(100*np.random.rand(20))
formatter = ticker.FormatStrFormatter('%1.2f%%')
ax.yaxis.set_major_formatter(formatter)
# 只显示y坐标轴右边的刻度
for tick in ax.yaxis.get_major_ticks():
tick.label1On = False
tick.label2On = True
tick.label2.set_color('green')
plt.show()
output_16_0.png
参考:
Matplotlib examples