4-5绘图细节设置
In [1]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
1.对轴的定义
- 当前的图表和子图可以使用plt.gcf()和plt.gca()获得,分别表示Get Current Figure和Get Current Axes
- fig.axes.get_xaxis().set_visible(False)定义轴是否可见
In [2]:
import matplotlib as mpl
mpl.rcParams['axes.titlesize']='20'#设置全局的标题大小,同理可设置其他的属性大小
In [3]:
x=range(10)
y=range(10)
fig=plt.gca()#获取当前轴
plt.plot(x,y)
plt.title('Group')#此标题大小被更改了!
fig.axes.get_xaxis().set_visible(False)#消除x轴
fig.axes.get_yaxis().set_visible(False)#消除y轴
math.round(),math.ceil(),math.floor()的区别:
- math.round():四舍五入取整
- math.ceil():向上取整
- math.floor():向下取整
2.hist直方图:对轴的刻度,是否可见的设置
In [4]:
import math
x=np.random.normal(loc=0.0,scale=1.0,size=300)
width=0.5
bins=np.arange(math.floor(x.min())-width,math.ceil(x.max()+width),width)#指定起始和终止值,间隔
ax=plt.subplot(111)#subplot不加s ,只画一个图
ax.spines['top'].set_visible(False)#设置上面轴不可见
ax.spines['right'].set_visible(False)#设置右面轴不可见
plt.tick_params(bottom='off',top='off',left='off',right='off')#去掉刻度标尺
plt.grid()
plt.hist(x,alpha=0.5,bins=bins)#画直方图hist
Out[4]:
3.labels的对齐方式和旋转角度设定分别是:horizontalalignment和rotation的参数设定
In [5]:
x=range(10)
y=range(10)
labels=['tangyudi' for i in range(10)]
fig,ax=plt.subplots()
plt.plot(x,y)
#rotation=45:旋转labels 角度,horizontalalignment='left':靠左对齐,
ax.set_xticklabels(labels,rotation=45,horizontalalignment='left')
Out[5]:
4.对图例放置位置的设定plt.legend(loc='position'):position的值自己设定
- plt.legend图例画在图里
In [6]:
x=np.arange(10)
for i in range(1,4):
plt.plot(x,i*x**2,label='Group %d'%i)
plt.legend(loc='best')#图例:loc='best'自动找最合适的位置,也可以自己设定位置参数如upper left
Out[6]:
In [7]:
x=np.arange(10)
for i in range(1,4):
plt.plot(x,i*x**2,label='Group %d'%i)
plt.legend(loc='center left')
Out[7]:
5.对图例放置位置的设定ax.legend(loc='position',bbox_to_anchor=(0.5,1.15),ncol=3 )
- ax.legend图例根据轴来定位,放在图外面
- bbox_to_anchor=(0.5,1.15)是设定图例位置的x,y坐标
- ncol=3 是横着显示3个图例
In [8]:
fig=plt.figure()
ax=plt.subplot(111)
x=np.arange(10)
for i in range(1,4):
plt.plot(x,i*x**2,label='Group %d'%i)
ax.legend(loc='upper center',bbox_to_anchor=(0.5,1.15),ncol=3)
Out[8]:
In [9]:
fig=plt.figure()
ax=plt.subplot(111)
x=np.arange(10)
for i in range(1,4):
plt.plot(x,i*x**2,label='Group %d'%i)
ax.legend(loc='upper center',bbox_to_anchor=(1.15,1.15),ncol=1)#ncol=1竖着显示
Out[9]:
6.定义图例的透明度在plt.legend()中设定framealpha的值
In [10]:
x=np.arange(10)
for i in range(1,4):
plt.plot(x,i*x**2,label='Group %d'%i,marker='o')
plt.legend(loc='upper right',framealpha=0.5)
Out[10]:
此资源来自https://www.cnblogs.com/AI-robort/,博客园的karina512。