Python数据可视化工具matplotlib(二)-- 图表的基本元素及样式参数

本文深入探讨了使用Python的Matplotlib库进行数据可视化的各种技巧,包括设置图表的标题、轴标签、轴边界、刻度和刻度标签,以及网格、坐标轴显示、线条样式、标记符号、颜色、风格参数和注解。此外,还介绍了如何调整刻度定位、格式和网格显示,以及如何保存图表。通过实例展示了如何创建和自定义各类图表,是Python数据可视化的重要参考资料。
摘要由CSDN通过智能技术生成

图表的基本元素及样式参数


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’(白色)

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jepson2017

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值