Matplotlib图表的基本元素

前言:Matplotlib作为python最基本的画图工具之一,需要了解它的基本元素才可调试出合适的图表。

主要为plt.plot()和pd.Dataframe().plot()&pd.Series().plot()以及plt.各种参数 () 的使用

1.图表的基本元素

'''
图名-->plt.title()
x轴标签-->plt.xlabel()
y轴标签-->plt.ylabel()
图例-->plt.legend(	'best'
	upper right
	upper left
	lower left
	lower right
	right
	center left
	center right
	lower center
	upper center
	center)
x轴边界-->plt.xlim()
y轴边界-->plt.ylim()
x刻度-->plt.xticks
y刻度-->plt.yticks
x刻度标签-->fig.set_xticklabels()
y刻度标签-->fig.set_yticklabels()
'''



df = pd.DataFrame(np.random.rand(10,2),columns=['A','B'])

fig=df.plot(figsize=(8,4)) 

plt.title('lalala')
plt.xlabel('xx')
plt.ylabel('yy')

plt.legend(loc='best')

plt.xlim([0,12])
plt.ylim([0,1.5])

plt.xticks(range(10))
plt.yticks([0,0.2,0.4,0.6,0.8,1.0,1.2])

fig.set_xticklabels("%.1f" %i for i in range(10))  
fig.set_yticklabels("%.2f" %i for i in [0,0.2,0.4,0.6,0.8,1.0,1.2])

# 这里x轴范围是0-12,但刻度只是0-9,刻度标签使得其显示1位小数

2.图表样式

'''
linestyle
color
marker
style(linestyle,marker,color)
alpha
colormap
grid-->表格
'''
s=pd.Series(np.random.randn(100).cumsum())
s.plot(linestyle='--',marker='.',color='r',grid=True,title='lala')
# 或者在添加title元素是用plt.title()

其中,cumsum()的用法为下:

df=pd.DataFrame(np.random.randn(100,4),columns=['A','B','C','D']).cumsum() # 或columns=list('ABCD')
df.plot(style='--',alpha=0.8,colormap='summer_r')
df.plot(style='--')

3.图标注解

df=pd.DataFrame(np.random.randn(10,2))
df.plot(style='--o')
plt.text(5,1,'Hello',fontsize=15)

4.子图绘制

4.1 figure对象

plt.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=<class 'matplotlib.figure.Figure'>, **kwargs)
fig1=plt.figure(num=1,figsize=(8,6))
plt.plot(np.random.rand(50).cumsum(),'k--') # rand产生>0的小数,randn正负小数都有
fig2=plt.figure(num=2,figsize=(8,6)) # num表示产生第二个图,若num同为1,则二条线在同一个图表中
plt.plot(50-np.random.rand(50).cumsum(),'--o')

4.2 建子图后填充图表

# 整体架构为fig,建立子图为ax,填充图表并以plt呈现图像
fig=plt.figure(figsize=(10,6),facecolor='gray')

ax1=fig.add_subplot(2,2,1) # 左数控制高度,中数控制宽度,右数只能是1
plt.plot(np.random.rand(50).cumsum(),'k--')
plt.plot(np.random.randn(50).cumsum(),'b--')

ax2=fig.add_subplot(2,2,2)
ax2.hist(np.random.randn(50),alpha=0.5)

ax4=fig.add_subplot(2,2,4)
df2=pd.DataFrame(np.random.rand(10,4),columns=list('abcd'))
ax4.plot(df2,alpha=0.5,linestyle='--',marker='.')

4.3 使用subplots子图数组填充图表

# 创建一个新的figure,并返回一个subplot对象的numpy数组 → plt.subplot

fig,axes = plt.subplots(2,3,figsize=(10,4))
ts = pd.Series(np.random.randn(1000).cumsum())
print(axes, axes.shape, type(axes))
# 生成图表对象的数组

ax1 = axes[0,1]
ax1.plot(ts)

# plt.subplots 参数调整
fig,axes = plt.subplots(2,2,sharex=True,sharey=True)
# sharex,sharey:是否共享x,y刻度

for i in range(2):
    for j in range(2):
        axes[i,j].hist(np.random.randn(500),color='k',alpha=0.5)
        
# wspace,hspace:用于控制宽度和高度的百分比,比如subplot之间的间距
plt.subplots_adjust(wspace=0,hspace=0)

4.4 多系列图绘制

plt.plot():

  • subplots,是否分别绘制系列(子图)
  • layout:绘制子图矩阵,按顺序填充
df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))
df = df.cumsum()
df.plot(style = '--.',alpha = 0.4,grid = True,figsize = (20,8),
       subplots = True,
       layout = (1,4),
       sharex = False)
plt.subplots_adjust(wspace=0,hspace=0.2)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值