python绘图之图例的添加和坐标轴的移动大法【转】

本文介绍了使用Python进行数据可视化的方法,包括如何添加图例并调整其位置,以及如何移动坐标轴来改善图表的可读性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:https://blog.youkuaiyun.com/lishangyin88/article/details/80260957

1.图例的添加

[python]  view plain  copy
  1. import pandas as pd  
  2. import numpy as np  
  3. import matplotlib.pyplot as plt  
  4. import matplotlib  
  5. %matplotlib inline  
  6. data1=np.random.normal(30,5,100)  
  7. data2=np.random.normal(50,6,100)  
  8. data3=np.random.normal(70,5,100)  
  9. data4=np.random.rand(100)  
  10. plt.plot(data1,label='label1')  
  11. plt.plot(data2,label='label2')  
  12. plt.plot(data3,label='label3')  
  13. plt.plot(data4,label='label4')  
  14. #bbox_to_anchor用于定位标签的位置和大小。前两个数值表示标签左下角的坐标,后两个表示标签的长度和高度  
  15. #ncol表示标签有几列,loc表示位置0表示最合适。mode 表示是水平填充坐标轴区域,  
  16. #borderaxespad一般为默认,表示图利与坐标轴区域的空间。  
  17. plt.legend(bbox_to_anchor=(0,1.02,1,0),ncol=2,loc=0,mode='expand',borderaxespad=0)  
  18. #xy表示指向的位置坐标,xytext表示注释文本框的左下角的坐标。  
  19. plt.annotate('Important Value',xy=(18,20),xytext=(20,10),arrowprops=dict(arrowstyle='->'))  

2.坐标轴的移动

[python]  view plain  copy
  1. x=np.linspace(-np.pi,np.pi,500,endpoint=True)  
  2. y=np.sin(x)  
  3. plt.plot(x,y)  
  4. ax=plt.gca()  
  5. #spines是指连接坐标轴的线,一共有上下左右四个。top/bottom/right/left  
  6. #上面的和右面的设置成无色  
  7. ax.spines['right'].set_color('none')  
  8. ax.spines['top'].set_color('none')  
  9. #把下面的和左面的线设置成(0,0)  
  10. ax.spines['bottom'].set_position(('data',0))  
  11. ax.spines['left'].set_position(('data',0))  
  12. ax.xaxis.set_ticks_position('bottom')  
  13. #设置刻度间隔是0.5的倍数。这里要注意引入matplotlib.  
  14. ax.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(0.5))  
  15. ax.ylim=(-1,1)  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值