import pandas as pd
unrate=pd.read_csv(r"F:\唐宇迪机器学习资料\机器学习\Python库代码(4个)\3-可视化库matpltlib\UNRATE.csv")
unrate["DATE"]=pd.to_datetime(unrate["DATE"])
print(unrate.headd(12))
DATE VALUE
0 1948-01-01 3.4
1 1948-02-01 3.8
2 1948-03-01 4.0
3 1948-04-01 3.9
4 1948-05-01 3.5
5 1948-06-01 3.6
6 1948-07-01 3.6
7 1948-08-01 3.9
8 1948-09-01 3.8
9 1948-10-01 3.7
10 1948-11-01 3.8
11 1948-12-01 4.0
这里pd.to_datetime()是对时间进行格式转换具体用法如下:
pd.to_datetime('2017/09/24',format='%Y/%m/%d')
Timestamp('2017-09-24 00:00:00')
#画出折线图
import matplotlib.pyplot as plt
plt.plot(unrate['DATE'][0:50],unrate['VALUE'][0:50],'r-')
#对x轴的区域标注倾斜
plt.xticks(rotation=45)#其中rotation是设置的倾斜角度
plt.xlabel('Month')
plt.ylabel('Unemployment Rate')
plt.title('Monthly Unemployment Trends,1948')
plt.show()
fig=plt.figure(figsize=(20,10))
ax1=fig.add_subplot(2,2,1)
plt.plot(unrate['DATE'][0:50],unrate['VALUE'][0:50],'r-')
#对x轴的区域标注倾斜
plt.xticks(rotation=45)
ax2=fig.add_subplot(2,2,2)
plt.plot(unrate['DATE'][51:100],unrate['VALUE'][51:100],'r-')
#对x轴的区域标注倾斜
plt.xticks(rotation=45)
ax3=fig.add_subplot(2,2,3)
plt.plot(unrate['DATE'][100:150],unrate['VALUE'][100:150],'r-')
#对x轴的区域标注倾斜
plt.xticks(rotation=45)
ax3=fig.add_subplot(2,2,4)
plt.plot(unrate['DATE'][151:200],unrate['VALUE'][151:200],'r-')
#对x轴的区域标注倾斜
plt.xticks(rotation=45)
plt.show()
plt.bar(left, height, width=0.8, bottom=None, kwargs)
left,height,width,bottom这四个参数确定了柱体的位置和大小
通过 facecolor(或fc) 关键字参数可以设置柱体颜色 fc=‘g’
通过 color 关键字参数 可以一次性设置多个颜色 color=‘rgb’
设置tick label
import matplotlib.pyplot as plt
data=[5,20,15,25,10]
labels=['Tom', 'Dick', 'Harry', 'Slim', 'Jim']
plt.bar(range(len(data)),data,width=0.4,fc='g',tick_label=labels)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
size = 5
x = np.arange(size)
a = np.random.random(size)
b = np.random.random(size)
plt.bar(x, a,width=0.4,label='a')
plt.bar(x, b,width=0.4,bottom=a, label='b')#其中bottom设置的谁在下面
plt.legend()
plt.show()
import numpy as np
import matplotlib.pyplot as plt
size = 5
x = np.arange(size)
a = np.random.random(size)
b = np.random.random(size)
c = np.random.random(size)
total_width, n = 0.8, 3
width = total_width / n
x = x - (total_width - width) / 2
plt.bar(x, a, width=width, label='a')
plt.bar(x + width, b, width=width, label='b')
plt.bar(x + 2 * width, c, width=width, label='c')
plt.legend()
plt.show()
import matplotlib.pyplot as plt
data = [5, 20, 15, 25, 10]
plt.barh(range(len(data)), data)
plt.show()
保存的时候遇到过保存空白图像的问题,是因为将plt.savefig()放到了plt.show()之后,
只要先保存在显示plt.show()就可以正常保存了。
dpi用于设置清晰度
pad_inches = 0用于设置导出图片时四周的白边
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0, 69, 1)
plt.plot(t, t, 'r', t, t**2, 'b')
label = ['t', 't**2']
plt.legend(label, loc='upper left')
plt.savefig(r'C:\Users\asus\Desktop\test.tif',dpi=300,pad_inches = 0)
plt.show()