Python中matplotlib库

注:我们一般用ax实际的画图,用fig去设置图的参数,控制图的整体
1.折线图画法

#打开.csv文件
from pandas import *
import matplotlib.pyplot as plt

fp = DataFrame(read_csv('UNRATE.csv'))
fp["DATE"] = to_datetime(fp["DATE"]) #转化成日期格式1995-09-30
#print(fp.head(5))

fp = DataFrame(read_csv('UNRATE.csv'))
fp["DATE"] = to_datetime(fp["DATE"]) #转化成日期格式1995-09-30
#print(fp.head(5))

#画图
first_12 = fp[0:12] #前12条数据
plt.plot(first_12["DATE"],first_12["VALUE"]) #x轴 y轴,离散点用plot会生成折线图
plt.xticks(rotation=45)#如果x轴标签比较长,可以适当旋转
plt.xlabel("date") #x轴的标签
plt.ylabel("unemployment rate") #y轴的标签
plt.title("mypythonPlot") #题目
plt.show()

在这里插入图片描述
2.子图

from pandas import *
from numpy import *
import matplotlib.pyplot as plt

fp = DataFrame(read_csv('UNRATE.csv'))
fp["DATE"] = to_datetime(fp["DATE"]) #转化成日期格式1995-09-30
#print(fp.head(5))
fp["MONTH"] = fp["DATE"].dt.month #只取数据的月份

first_12 = fp[0:12] #前12条数据
second_12 = fp[12:24] #第12到23条数据

#fig = plt.figure(figsize=(3,3)) #figsize=(3,3)第一个参数是长,第二个参数是宽
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1) #子图,2行列个图,最后1是表示第1个图
ax2 = fig.add_subplot(2,1,2) #子图,2行列个图,最后2是表示第2个图

ax1.plot(first_12["MONTH"],first_12["VALUE"],c="red",label="1948") #c="red"线条颜色是红色
ax1.plot(second_12["MONTH"],second_12["VALUE"],c="blue",label="1949") #在同一张图上画12到23条数据
ax1.legend(loc=0) #legend()就是尝试在图例框中添加内容,0表示best

ax2.plot(second_12["MONTH"],second_12["VALUE"],c="blue") #在第二张图上画12到23条数据
ax2.legend(loc=0)

plt.xticks(rotation=90)#如果x轴标签比较长,可以适当旋转

plt.show()

在这里插入图片描述
3.柱形图

from pandas import *
from numpy import *
import matplotlib.pyplot as plt


fp = DataFrame(read_csv('fandango_score_comparison.csv'))

col_names = ["RT_user_norm","Metacritic_user_nom","IMDB_norm","Fandango_Ratingvalue","Fandango_Stars"]
#五家评分公司

print(col_names)
print(len(col_names)) #6

bar_heights = fp.ix[0,col_names].values #.ix[m,n] 取第m行第n列的数据
print(bar_heights)
bar_positions = arange(5) + 0.75
print(bar_positions)

fig,ax = plt.subplots()

ax.bar(bar_positions,bar_heights,0.3) #画bar型图,0.3是柱的宽度
#如果要横着画,就是ax.bar(bar_heights,bar_positions,0.3)

plt.show()

在这里插入图片描述
4.散点图

from pandas import *
from numpy import *
import matplotlib.pyplot as plt


fp = DataFrame(read_csv('fandango_score_comparison.csv'))

fig,ax = plt.subplots()
ax.scatter(fp["Fandango_Ratingvalue"],fp["RT_user_norm"]) #x轴,y轴数据

在这里插入图片描述
5.盒图

from pandas import *
from numpy import *
import matplotlib.pyplot as plt


fp = DataFrame(read_csv('fandango_score_comparison.csv'))
print(fp["RT_user_norm"])

fig,ax = plt.subplots()
ax.boxplot(fp["RT_user_norm"]) #画盒图
ax.set_xticklabels(["Rotten Tomatoes"])
ax.set_ylim(0,5) #y的范围

plt.show()

在这里插入图片描述
☆持续更新

猜你喜欢

转载自blog.csdn.net/fenfenxhf/article/details/82847921