Python数据可视化——坐标轴&画板

在调用matplotlib库中的pyplot模块时,许多函数都是对当前的画板Figure或画布Axes对象进行处理。有两个经常使用的命令可以指向的获得当前的figureaxes

# 在plt.plot()中,通过使用 
plt.gcf()  # Get Current Figure
# 获得当前使用的画板

plt.gca()  # Get Current Axes
# 获得当前使用的画布

改变坐标轴的默认位置

在获得当前的 画板 或 画纸 之后就可以对其进行具体的实质性操作了。在调用画纸plt.gca()之后一些操作变得更加方便。这里仍旧使用前一篇文章的例子example.txt数据。

年份	PM2.5	PM10	SO2	NO2	CO-95per
2015/1/1	72	114	19	48	1.5
2015/2/1	73	97	14	39	1.6
2015/3/1	40	59	10	32	1.3
2015/4/1	44	84	13	33	1.2
2015/5/1	28	58	10	27	1
2015/6/1	20	44	9	22	0.8
2015/7/1	30	56	11	27	1
2015/8/1	34	68	13	29	1
2015/9/1	29	52	11	28	1.1
2015/10/1	53	105	18	41	1.3
2015/11/1	34	60	13	34	1.3
2015/12/1	41	66	15	38	1.2
2016/1/1	43	69	13	40	1.6

首先,将数据导入pandas

import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['font.sans-serif'] = ['SimHei']   # 设置简黑字体
matplotlib.rcParams['axes.unicode_minus'] = False  # 正常显示负号

filename = r'...\\example.txt'  # 设置文件存储的绝对或相对路径
data = pd.read_table(filename, encoding="gbk")

当使用plt.gca()函数时必须将画板先进行声明。在画纸axes中spine()函数,表示画纸边框以及刻度线的设计。绘制下面的图片我们需要进行抹掉一些边框,设置好x、y轴,并将x轴对应在y轴得相应位置处。

plt.figure(facecolor='lightgreen')  # 声明一个亮绿色画板
plt.xlabel("年份") # 为x轴打上标签
plt.ylabel("PM2.5")  # 为y轴打上标签
ax = plt.gca()  #  获得坐标轴对象 并 赋给ax

# 抹掉边框
ax.spines['right'].set_color('none')   # 将右边框颜色设置为空 (抹掉右边框)
ax.spines['top'].set_color('none')  # 将上边框颜色设置为空 (抹掉上边框)

# 设置x、y轴
ax.xaxis.set_ticks_position('bottom')  # 指定下边框作为 x 轴
ax.yaxis.set_ticks_position('left')  # 指定左边的边为 y 轴

# 设置x、y轴的位置
ax.spines['bottom'].set_position(('data', 40))  # 此时设置的bottom(也就是指定的x轴)绑定到y轴等于40这个点上
ax.spines['left'].set_position(('data', 0)) # y轴对应到x的初始点上

plt.xticks(rotation=60)  # 旋转x轴坐标
plt.show()

在这里插入图片描述

更改坐标轴刻度

对坐标轴刻度的更改,有更改坐标轴的范围、修改坐标轴的样式、修改坐标刻度的数据类型以及更改坐标轴显示刻度的密度。
更改坐标轴的数据类型
将x轴坐标修改为日期类型数据,并显示。

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y/%m/%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())

这里面的plt.gca() 等同为对象 ax

将y轴坐标修改为浮点型数据,并显示

ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%1.1f'))

在这里插入图片描述
修改坐标轴的刻度

x_major_locator=plt.MultipleLocator(1)  # 把x轴的刻度间隔设置为1,并存在变量里
y_major_locator=plt.MultipleLocator(5)  # 把y轴的刻度间隔设置为5,并存在变量里

ax.xaxis.set_major_locator(x_major_locator)  # 把x轴的主刻度设置为1的倍数
ax.yaxis.set_major_locator(y_major_locator) # 把y轴的主刻度设置为5的倍数

这样x轴刻度的间距就没有发生改变,而y轴刻度修改为以5
为间隔的数列。
在这里插入图片描述

修改坐标轴的样式

使用函数tick_params()修改坐标轴的样式。
参数axis的值为’x’、‘y’、‘both’,分别代表设置X轴、Y轴以及同时设置,默认值为’both’。

ax1.tick_params(axis='x',width=2,colors='gold')
ax2.tick_params(axis='y',width=2,colors='gold')
ax3.tick_params(axis='both',width=2,colors='gold')

ax1将x轴画成金色。ax2将y轴画成金色。ax3将x、y轴都画成金色。

参数which的值为 ‘major’、‘minor’、‘both’,分别代表设置主刻度线、副刻度线以及同时设置,默认值为’major’

ax1.tick_params(which='major',width=2,colors='gold')
ax2.tick_params(which='minor',width=2,colors='gold')
ax3.tick_params(which='both',width=2,colors='gold')

更多关于tick_params参数设置

修改坐标轴范围
由于x轴的数据是时间数据,指定时间数据的范围 需要调用datetime库。首先要把数据框中的年份数据转换为datetime类型。

data["年份"] = pd.to_datetime(data["年份"])
ax.set_xlim([datetime.date(2014,11,1), datetime.date(2016, 3,1)])
ax.set_ylim([10, 80])
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib
import datetime
matplotlib.rcParams['font.sans-serif'] = ['SimHei']   # 设置简黑字体
matplotlib.rcParams['axes.unicode_minus'] = False  # 正常显示负号

filename = r'。。。\\example.txt'
data = pd.read_table(filename, encoding="gbk")

plt.figure()  # 声明一个亮绿色画板
plt.xlabel("年份") # 为x轴打上标签
plt.ylabel("PM2.5")  # 为y轴打上标签


ax = plt.gca()  #  获得坐标轴对象 并 赋给ax

data["年份"] = pd.to_datetime(data["年份"])
ax.set_xlim([datetime.date(2014,11,1), datetime.date(2016, 3,1)])  # 设置x轴的范围
ax.set_ylim([10, 80])  # 设置y轴的范围

# 抹掉边框
ax.spines['right'].set_color('none')   # 将右边框颜色设置为空 (抹掉右边框)
ax.spines['top'].set_color('none')  # 将上边框颜色设置为空 (抹掉上边框)

# 设置x、y轴
ax.xaxis.set_ticks_position('bottom')  # 指定下边框作为 x 轴
ax.yaxis.set_ticks_position('left')  # 指定左边的边为 y 轴

# 设置x、y轴的位置
ax.spines['bottom'].set_position(('data', 40))  # 此时设置的bottom(也就是指定的x轴)绑定到y轴等于40这个点上
# ax.spines['left'].set_position(('data', 0)) # y轴对应到x的初始点上
!在将x轴坐标设置为时间周后  这里y轴对应到x的初始点上  目前在困扰着我

plt.plot(data["年份"], data["PM2.5"])
plt.xticks(rotation=60)  # 旋转x轴标签的角度

import matplotlib.ticker as ticker
import matplotlib.dates as mdates
ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%1.1f'))
# plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y/%m/%d'))
# plt.gca().xaxis.set_major_locator(mdates.DayLocator())
# plt.gcf().autofmt_xdate()  # 自动旋转日期标记

x_major_locator=plt.MultipleLocator(30)  # 把x轴的刻度间隔设置为1,并存在变量里
y_major_locator=plt.MultipleLocator(10)  # 把y轴的刻度间隔设置为5,并存在变量里

ax.xaxis.set_major_locator(x_major_locator)  # 把x轴的主刻度设置为1的倍数
ax.yaxis.set_major_locator(y_major_locator) # 把y轴的主刻度设置为5的倍数

plt.show()  # 显示图像

在这里插入图片描述

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值