折线图
折线图的绘制
import pandas as pd
unrate = pd.read_csv('unrate.csv') unrate['DATE'] = pd.to_datetime(unrate['DATE']) # 转换成datetime的格式
import matplotlib.pyplot as plt
first_twelve = unrate[0:12]
plt.plot(first_twelve['DATE'],first_twelve['VALUE']) # x轴,y轴
plt.xticks(rotation=45) # x轴的标签倾斜45度
plt.xlabel('Month')
plt.ylabel('Unemployment Rate')
plt.title('Monthly Unemployment Trends,1948')
plt.show()
在一张图中绘制2条折线
unrate['MONTH'] = unrate['DATE'].dt.month
unrate['MONTH'] = unrate['DATE'].dt.month
fig = plt.figure(figsize=(6,3))
plt.plot(unrate[0:12]['MONTH'],unrate[0:12]['VALUE'],c='red') # 折线颜色为红色
plt.plot(unrate[12:24]['MONTH'],unrate[12:24]['VALUE'],c='blue')
plot.show()
在一张图中绘制n条折线
fig = plt.figure(figsize=(10,6))
color = ['red','blue','green','orange','black']
for i in range(5):
start_index = i*12
end_index = (i+1)*12
subset = unrate[start_index:end_index]
label = str(1948 + i)
plt.plot(subset['MONTH'],subset['VALUE'],c=color[i],label=label) # label:在图中显示的标签内容
plt.legend(loc='best') # 只要设置了这条语句,label才能显示出来,best表示的是放置label的位置,还可以有left,right,upper left等等
plt.show()
子图操作
import matplotlib.pyplot as plt
import numpy as np fig = plt.figure(figsize=(6,3)) # 设置绘图区间,figsize为绘图的大小,指宽度和高度 ax1 = fig.add_subplot(2,2,1)
ax1.plot(np.random.randint(1,5,5),np.arange(5)) ax2 = fig.add_subplot(2,2,2) ax3 = fig.add_subplot(2,2,4) plt.show()
柱形图(横竖柱形图)
import matplotlib.pyplot as plt from numpy import arange num_cols = ['RT','Meta',"IMDB',Fandango'] bar_heights = norm_review.ix[0,num_cols].values bar_positions = arange(5) + 0.75 # [0.75,1.75,2.75,3.75,4.75]表示与原点的距离
tick_positions = range(1,6) fig,ax = plt.subplots()
ax.bar(bar_positions,bar_heights,0.3) # 0.3表示柱子的宽度,ax.barh表示是横着画柱形图
ax.set_xticks(tick_positions)
ax.set_xticklabels(num_cols,rotation=45) # x轴的label倾斜45度
ax.set_xlabel('Rating Source')
ax.set_ylabel('Average Rating')
ax.set_title('Average User Rating For Avengers:Age of Ultron(2015)')
plt.show()
散点图
fig,ax = plt.subplots() ax.scatter(norm_reviews['Fandango'],norm_reviews['RT'])
ax.set_xlabel('Fandango')
ax.set_ylabel('Rotten Tomatoes')
plt.show()
fig,ax = plt.subplots() ax.hist(norm_reviews['Fandango_Ratingvalue'] ax.hist(norm_reviews['Fandango_Ratingvalue'],bins=20) # bins指柱形图的个数 ax.hist(norm_reviews['Fandango_Ratingvalue'],range=(4,5),bins=20) # range指定范围,显示4-5的数据
ax1.set_ylim(0,50) # y轴显示数值为0-50的区间 plt.show()
盒图
num_cols = ['RT','Meta','IMDB','Fandango']
fig,ax = plt.subplots()
ax.boxplot(norm_reviews[num_cols].values)
ax.set_xticklabels(num_cols,rotation=90) # x轴的label旋转90度
ax.set_ylim(0,5)
plt.show()
ax.tick_params(bottom='off',top='off',left='off',right='off') # 去掉上下左右的标尺
cb_dark_blue = (0/255,107/255,164/255) # 设置颜色
ax.text(2005,87,'Men') # 在折线图中显示标签
seaborn
import seaborn as sns import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt %matplotlib inline def sinplot(flip=1): x = np.linspace(0,14,100) # 在0-14之间找出100个点 for i in range(1,7): # 画6条线 plt.plot(x,np.sin(x+i*0.5)*(7-i)*flip)
sns.set_style('tick') # whitegrid,tick,dark,white,默认的话用set()就可以了
sinplot(-1) # -1可以填也可以不填
sns.despine(offset=10,left=True) # 将右边的和上边的轴线都去掉,offset表示偏移值
seaborn有五种风格:whitegrid,tick,dark,white
sns.set_style('whitegrid') # 设置类型
data = np.random.normal(size=(20,6)) + np.arange(6)/2
sns.boxplot(data = data,palette='deep') # palette=sns.color_palette("hls",8)
# sns.violinplot(data) #另一种风格的图
sns.set_context('paper') # 还可以有talk,poster,notebook
sns.set_context('notebook',font_scale=1.5,rc={"lines.linewidth":2.5})
调色板
import seaborn as sns import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt
color_palette()能传入任何Matplotlib所支持的颜色
color_palette()不写参数则默认颜色
set_palette()设置所有图的颜色
current_palette = sns.color_palette() # 6个默认的颜色循环主题:deep,muted,pastel,bright,dark,colorblind
sns.palplot(current_palette)
sns.palplot(sns.color_palette('hls',8)) # hls是一个颜色空间,8指的是传入8中颜色
sns.palplot(sns.hls_palette(8,l=.3,s=.8)) # 控制颜色的亮度和饱和度
sns.palplot(sns.color_palette('Paired’,8)) # 8对颜色
sns.palplot(sns.color_palette('BuGn')) # 渐变,由浅到深
sns.palplot(sns.color_palette('BuGn_r')) #_r,由深到浅
sns.palplot(sns.color_palette('cubehelix',8))
sns.palplot(sns.cubehelix_palette('cubehelix',8,start=.5,rot=-.75))
sns.palplot(sns.light_palette("green",reverse=True))
sns.palplot(sns.dark_palette('purple')
x,y = np.random.multivariate_normal([0,0],[[1,-.5],[-.5,1]],size=300).T
pal = sns.dark_palette("green",as_cmap=True)
sns.kdeplot(x,y,cmap=pal)