Python数据可视化工具matplotlib(二)-- 图表的基本元素及样式参数
图表的基本元素及样式参数import pandas as pdimport numpy as npimport matplotlib.pyplot as plt%matplotlib inline图名、图例、轴标签、轴边界、轴刻度、轴刻度标签等df=pd.DataFrame(np.random.rand(10,2), columns=['A', 'B'])df.head()fig=df.plot(
·
图表的基本元素及样式参数
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
图名、图例、轴标签、轴边界、轴刻度、轴刻度标签等
df=pd.DataFrame(np.random.rand(10,2), columns=['A', 'B'])
df.head()
fig=df.plot(figsize=(6,4))
#figsize: 创建图表窗口,设置窗口大小
# 创建图表对象,并赋值fig
plt.title("Interrsting Graph") # 图名
plt.xlabel("Plot Number") # x轴标签
plt.ylabel("Important var") # y轴标签
plt.legend(loc=0) # 显示图例,loc表示位置,可以用数字,也可以用'best
# best:0自适应方式
# upper right:1、upper left:2、lower left:3、lower fight:4、right:5、center left:6、center right:7、lower center:8、upper center:9、center:10
plt.xlim([0,12]) # x轴边界
plt.ylim([0,1.2]) #y轴边界
plt.xticks(range(12)) # 设置x刻度
plt.yticks([0.0, 0.3, 0.6, 0.9, 1.2]) # 设置y刻度
fig.set_xticklabels("%.1f" %i for i in range(12)) # x轴刻度标签
fig.set_yticklabels("%.2f" %i for i in [0.0, 0.3, 0.6, 0.9, 1.2]) # y轴刻度标签
# 范围只限定图表的长度,刻度则是决定显示的标尺 :这里x轴的范围是0-12,但刻度只有0-11,刻度标签使得其显示1位小数
# 轴标签则是显示刻度的标签

网格、刻度属性、坐标轴显示
x=np.linspace(-np.pi, np.pi, 256, endpoint=True)
c,s = np.cos(x), np.sin(x)
plt.plot(x, c)
plt.plot(x, s)
plt.grid(True, linestyle='--', color='gray', linewidth='0.5', axis='both')
# 显示网格,线型,颜色,宽度,axis: x/y/both 显示x/y/两者的格网
plt.tick_params(bottom=True, top=False, left=True, right=True)
# 刻度显示
plt.tick_params(color='red', labelcolor='blue', length=10, width=3,labelright=True, labelsize=10,pad=10)
# color :刻度颜色,labelcolor:刻度标签颜色,如果同时设置刻度颜色和刻度标签颜色:colors='blue'
# labelright: 显示右侧刻度标签,width:刻度宽度,length:刻度长度
# labelsize:刻度标签字体大小:数字、"medium"、"large", pad: 设置刻度线和标签之间的距离
import matplotlib
matplotlib.rcParams['xtick.direction'] = 'in'
matplotlib.rcParams['ytick.direction'] = 'inout'
# 设置刻度方向,in、out、inout
#plt.axis('off') # 关闭坐标轴
#frame=plt.gca()
#frame.axes.get_xaxis().set_visible(False) # x轴不可见
#frame.axes.get_yaxis().set_visible(False) # y轴不可见

linestyle参数设置
plt.plot([i**2 for i in range(100)],
linestyle=':'
)
# '-'、'--'、'-.'、':'

marker参数:线上的点的样式
s=pd.Series(np.random.randn(100).cumsum())
s.plot(linestyle='-.', marker='<')
# '.' point marker
# ',' pixel marker
# 'o' circle marker
# 'v' triangle_down marker
# '^' triangle_up marker
# '<' triangle_left marker
# '>' triangle_right marker
# '1' tri_down marker
# '2' tri_up marker
# '3' tri_left marker
# '4' tri_right marker
# 's' square marker
# 'p' pentagon marker
# '*' star marker
# 'h' hexagon1 marker
# 'H' hexagon2 marker
# '+' plus marker
# 'x' x marker
# 'D' diamond marker
# 'd' thin_diamond marker
# '|' vline marker
# '_' hline marker

color参数
plt.hist(np.random.randn(100),
color = 'r',alpha = 0.8)
# alpha:0-1,透明度
# 常用颜色简写:red-r, green-g, black-k, blue-b, yellow-y

style参数,可以包含linestyle,marker,color
ts = pd.Series(np.random.randn(1000).cumsum(), index=pd.date_range('1/1/2000', periods=1000))
ts.plot(style = '--g.',grid = True)
# style → 风格字符串,这里包括了linestyle(-),marker(.),color(g)
# plot()内也有grid参数

刻度
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
t = np.arange(0.0, 100.0, 1)
s = np.sin(0.1*np.pi*t)*np.exp(-t*0.01)
ax = plt.subplot(111) #注意:一般都在ax中设置,不再plot中设置
plt.plot(t,s,'--*')
plt.grid(True, linestyle = "--",color = "gray", linewidth = "0.5",axis = 'both')
# 网格
xmajorLocator = MultipleLocator(10) # 将x主刻度标签设置为10的倍数
xmajorFormatter = FormatStrFormatter('%.0f') # 设置x轴标签文本的格式
xminorLocator = MultipleLocator(5) # 将x轴次刻度标签设置为5的倍数
ymajorLocator = MultipleLocator(0.5) # 将y轴主刻度标签设置为0.5的倍数
ymajorFormatter = FormatStrFormatter('%.1f') # 设置y轴标签文本的格式
yminorLocator = MultipleLocator(0.1) # 将此y轴次刻度标签设置为0.1的倍数
ax.xaxis.set_major_locator(xmajorLocator) # 设置x轴主刻度
ax.xaxis.set_major_formatter(xmajorFormatter) # 设置x轴标签文本格式
ax.xaxis.set_minor_locator(xminorLocator) # 设置x轴次刻度
ax.yaxis.set_major_locator(ymajorLocator) # 设置y轴主刻度
ax.yaxis.set_major_formatter(ymajorFormatter) # 设置y轴标签文本格式
ax.yaxis.set_minor_locator(yminorLocator) # 设置y轴次刻度
ax.xaxis.grid(True, which='both') #x坐标轴的网格使用主刻度
ax.yaxis.grid(True, which='minor') #y坐标轴的网格使用次刻度
# which:格网显示
#删除坐标轴的刻度显示
#ax.yaxis.set_major_locator(plt.NullLocator())
#ax.xaxis.set_major_formatter(plt.NullFormatter())

注解
df = pd.DataFrame(np.random.randn(10,2))
df.plot(style = '--o')
plt.text(5,0.5,'hahaha',fontsize=10)
# 注解 → 横坐标,纵坐标,注解字符串

图表输出
df = pd.DataFrame(np.random.randn(1000, 4), columns=list('ABCD'))
df = df.cumsum()
df.plot(style = '--.',alpha = 0.5)
plt.legend(loc = 'upper left')
plt.savefig('E:/test/pic.png',
dpi=400,
bbox_inches = 'tight',
facecolor = 'g',
edgecolor = 'b')
# 可支持png,pdf,svg,ps,eps…等,以后缀名来指定
# dpi是分辨率
# bbox_inches:图表需要保存的部分。如果设置为‘tight’,则尝试剪除图表周围的空白部分。
# facecolor,edgecolor: 图像的背景色,默认为‘w’(白色)

更多推荐
所有评论(0)