matplotlib坐标轴标注画图时怎么调整坐标轴上上刻度的大小

在 SegmentFault,解决技术问题
每个月,我们帮助 1000 万的开发者解决各种各样的技术问题。并助力他们在技术能力、职业生涯、影响力上获得提升。
一线的工程师、著名开源项目的作者们,都在这里:
获取验证码
已有账号?
标签:至少1个,最多5个
双y轴坐标轴图
今天利用matplotlib绘图,想要完成一个双坐标格式的图。
fig=plt.figure(figsize=(20,15))
ax1=fig.add_subplot(111)
ax1.plot(demo0719['TPS'],'b-',label='TPS',linewidth=2)
ax2=ax1.twinx()#这是双坐标关键一步
ax2.plot(demo0719['successRate']*100,'r-',label='successRate',linewidth=2)
横坐标设置时间间隔
import matplotlib.dates as mdate
ax1.xaxis.set_major_formatter(mdate.DateFormatter('%Y-%m-%d %H:%M:%S'))#设置时间标签显示格式
plt.xticks(pd.date_range(demo0719.index[0],demo0719.index[-1],freq='1min'))
纵坐标设置显示百分比
import matplotlib.ticker as mtick
fmt='%.2f%%'
yticks = mtick.FormatStrFormatter(fmt)
ax2.yaxis.set_major_formatter(yticks)
在matplotlib中,整个图像为一个Figure对象。在Figure对象中可以包含一个,或者多个Axes对象。每个Axes对象都是一个拥有自己坐标系统的绘图区域。其逻辑关系如下:一个Figure对应一张图片。
Title为标题。Axis为坐标轴,Label为坐标轴标注。Tick为刻度线,Tick Label为刻度注释。
Title为标题。Axis为坐标轴,Label为坐标轴标注。Tick为刻度线,Tick Label为刻度注释。
add_subplot()
pyplot.figure()是返回一个Figure对象的,也就是一张图片。
The Axes instance will be returned.
ax = twinx()
create a twin of Axes for generating a plot with a sharex x-axis but independent y axis. The y-axis of self will have ticks on left and the returned axes will have ticks on the right.意思就是,创建了一个独立的Y轴,共享了X轴。双坐标轴!
类似的还有twiny()
ax1.xaxis.set_major_formatter
Set the formatter of the major ticker
ACCEPTS: A Formatter instance
DateFormatter()
这是一个类,创建一个时间格式的实例。
strftime方法(传入格式化字符串)。
strftime(dt, fmt=None)
Refer to documentation for datetime.strftime.
fmt is a strftime() format string.
FormatStrFormatter()
Use a new-style format string (as used by str.format()) to format the tick. The field formatting must be labeled x定义字符串格式。
plt.xticks
# return locs, labels where locs is an array of tick locations and
# labels is an array of tick labels.
locs, labels = xticks()
# set the locations of the xticks
xticks( arange(6) )
# set the locations and labels of the xticks
xticks( arange(5), ('Tom', 'Dick', 'Harry', 'Sally', 'Sue') )
#coding:utf-8
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.dates as mdate
import matplotlib.ticker as mtick
import numpy as np
import pandas as pd
mpl.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
mpl.rcParams['axes.unicode_minus']=False #用来正常显示负号
mpl.rc('xtick', labelsize=20) #设置坐标轴刻度显示大小
mpl.rc('ytick', labelsize=20)
font_size=30
#matplotlib.rcParams.update({'font.size': 60})
%matplotlib inline
plt.style.use('ggplot')
data=pd.read_csv('simsendLogConvert_01.csv',index_col=0,encoding='gb2312',parse_dates=True)
columns_len=len(data.columns)
data_columns=data.columns
for x in range(0,columns_len,2):
print('第{}列'.format(x))
total=data.ix[:,x]
print('第{}列'.format(x+1))
successRate=(data.ix[:,x+1]/data.ix[:,x]).fillna(0)
yLeftLabel=data_columns[x]
yRightLable=data_columns[x+1]
print('------------------开始绘制类型{}曲线图------------------'.format(data_columns[x]))
fig=plt.figure(figsize=(25,20))
ax1=fig.add_subplot(111)
#绘制Total曲线图
ax1.plot(total,color='#4A7EBB',label=yLeftLabel,linewidth=4)
# 设置X轴的坐标刻度线显示间隔
ax1.xaxis.set_major_formatter(mdate.DateFormatter('%Y-%m-%d %H:%M:%S'))#设置时间标签显示格式
plt.xticks(pd.date_range(data.index[0],data.index[-1],freq='1min'))#时间间隔
plt.xticks(rotation=90)
#设置双坐标轴,右侧Y轴
ax2=ax1.twinx()
#设置右侧Y轴显示百分数
fmt='%.2f%%'
yticks = mtick.FormatStrFormatter(fmt)
# 绘制成功率图像
ax2.set_ylim(0,110)
ax2.plot(successRate*100,color='#BE4B48',label=yRightLable,linewidth=4)
ax2.yaxis.set_major_formatter(yticks)
ax1.set_xlabel('Time',fontsize=font_size)
ax1.set_ylabel(yLeftLabel,fontsize=font_size)
ax2.set_ylabel(yRightLable,fontsize=font_size)
legend1=ax1.legend(loc=(.02,.94),fontsize=16,shadow=True)
legend2=ax2.legend(loc=(.02,.9),fontsize=16,shadow=True)
legend1.get_frame().set_facecolor('#FFFFFF')
legend2.get_frame().set_facecolor('#FFFFFF')
plt.title(yLeftLabel+'&'+yRightLable,fontsize=font_size)
plt.savefig('D:\\JGT\\Work-YL\\01布置的任务\\04绘制曲线图和报告文件\\0803\\出图\\{}-{}'.format(yLeftLabel.replace(r'/',' '),yRightLable.replace(r'/',' ')),dpi=300)
1 收藏&&|&&6
你可能感兴趣的文章
31 收藏,2.5k
2 收藏,1.7k
本作品采用 署名-非商业性使用-禁止演绎 4.0 国际许可协议 进行许可
我用了这一句plt.xticks(pd.date_range(current_time,periods = 5,freq='1min')) 但图像上的时间轴值只重叠显示最后一刻度,是跟用了循环有关吗??因为不知道你的data.index[0],data.index[-1]是什么,所以不知道怎么理解xticks这一句,能否解答下?非常感谢~
我用了这一句plt.xticks(pd.date_range(current_time,periods = 5,freq='1min')) 但图像上的时间轴值只重叠显示最后一刻度,是跟用了循环有关吗??因为不知道你的data.index[0],data.index[-1]是什么,所以不知道怎么理解xticks这一句,能否解答下?非常感谢~
分享到微博?
我要该,理由是:python matplotlib绘图设置坐标轴刻度、文本 - CSDN博客
python matplotlib绘图设置坐标轴刻度、文本
总结matplotlib绘图如何设置坐标轴刻度大小和刻度。
from pylab import *
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
xmajorLocator
= MultipleLocator(20) #将x主刻度标签设置为20的倍数
xmajorFormatter = FormatStrFormatter('%1.1f') #设置x轴标签文本的格式
xminorLocator
= MultipleLocator(5) #将x轴次刻度标签设置为5的倍数
ymajorLocator
= MultipleLocator(0.5) #将y轴主刻度标签设置为0.5的倍数
ymajorFormatter = FormatStrFormatter('%1.1f') #设置y轴标签文本的格式
yminorLocator
= MultipleLocator(0.1) #将此y轴次刻度标签设置为0.1的倍数
t = arange(0.0, 100.0, 1)
s = sin(0.1*pi*t)*exp(-t*0.01)
ax = subplot(111) #注意:一般都在ax中设置,不再plot中设置
plot(t,s,'--b*')
#设置主刻度标签的位置,标签文本的格式
ax.xaxis.set_major_locator(xmajorLocator)
ax.xaxis.set_major_formatter(xmajorFormatter)
ax.yaxis.set_major_locator(ymajorLocator)
ax.yaxis.set_major_formatter(ymajorFormatter)
#显示次刻度标签的位置,没有标签文本
ax.xaxis.set_minor_locator(xminorLocator)
ax.yaxis.set_minor_locator(yminorLocator)
ax.xaxis.grid(True, which='major') #x坐标轴的网格使用主刻度
ax.yaxis.grid(True, which='minor') #y坐标轴的网格使用次刻度
show()绘图如下:
如果仔细看代码,可以得知,设置坐标轴刻度和文本主要使用了&MultipleLocator&、&FormatStrFormatter&方法。
这两个方法来自matplotlib安装库里面ticker.py文件;&MultipleLocator(Locator)&表示将刻度标签设置为Locator的倍数,&FormatStrFormatter&表示设置标签文本的格式,代码中&%1.1f&表示保留小数点后一位,浮点数显示。
相应的方法还有:
除了以上方法,还有另外一种方法,那就是使用xticks方法(yticks,x,y表示对应坐标轴),xticks用法可在python cmd下输入以下代码查看:
import matplotlib.pyplot as plt
help(plt.xticks)
代码如下:
import numpy as np
import matplotlib.pyplot as plt
fig,ax = plt.subplots()
x = [1,2,3,4,5]
y = [0,2,5,9,15]
#ax is the axes instance
group_labels = ['a', 'b','c','d','e']
plt.plot(x,y)
plt.xticks(x, group_labels, rotation=0)
plt.grid()
plt.show()
绘图如下:
上图中使用了&plt.xticks&方法设置x轴文本,标签文本使用group_labels中的内容,因此可以根据需要修改group_labels中的内容。
网上看到的另一种方法,代码如下:
import matplotlib.pyplot as pl
import numpy as np
from matplotlib.ticker import MultipleLocator, FuncFormatter
x = np.arange(0, 4*np.pi, 0.01)
y = np.sin(x)
pl.figure(figsize=(10,6))
pl.plot(x, y,label=&$sin(x)$&)
ax = pl.gca()
def pi_formatter(x, pos):
比较罗嗦地将数值转换为以pi/4为单位的刻度文本
m = np.round(x / (np.pi/4))
if m%2==0: m, n = m/2, n/2
if m%2==0: m, n = m/2, n/2
if m == 0:
return &0&
if m == 1 and n == 1:
return &$\pi$&
if n == 1:
return r&$%d \pi$& % m
if m == 1:
return r&$\frac{\pi}{%d}$& % n
return r&$\frac{%d \pi}{%d}$& % (m,n)
# 设置两个坐标轴的范围
pl.ylim(-1.5,1.5)
pl.xlim(0, np.max(x))
# 设置图的底边距
pl.subplots_adjust(bottom = 0.15)
pl.grid() #开启网格
# 主刻度为pi/4
ax.xaxis.set_major_locator( MultipleLocator(np.pi/4) )
# 主刻度文本用pi_formatter函数计算
ax.xaxis.set_major_formatter( FuncFormatter( pi_formatter ) )
# 副刻度为pi/20
ax.xaxis.set_minor_locator( MultipleLocator(np.pi/20) )
# 设置刻度文本的大小
for tick in ax.xaxis.get_major_ticks():
tick.label1.set_fontsize(16)
pl.legend()
pl.show()绘图如下:
特此记录。
本文已收录于以下专栏:
相关文章推荐
基本的文本命令
原文:Basic text commands
译者:飞龙
协议:CC BY-NC-SA 4.0
text在Axes的任意位置添加文本。命令式:matplotli...
在图形中,通过text添加纯文本的注释
text所有相关的参数:官网链接
#!/usr/bin/python
#coding: utf-8
import numpy as np
#!/usr/bin/env python#-*- coding: utf-8 -*- #---------------------------------------------------#演示M...
使用matplotlib的示例:调整字体-设置刻度、坐标、colormap和colorbar等
&&& import numpy as np
&&& import matplotlib.pyplot as plt
&&& x=np.arange(-5,5,0.01)
&&& y=x**3
这里直接用代码片段说明一下如何设置刻度、图例和坐标标签字体大小。import matplotlib.pyplot as plt# 代码中的“...”代表省略的其他参数
ax = plt.subplot...
ax = plt.subplot(111)
# 设置刻度字体大小
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
# 设置坐标标签字体大小
axes = plt.gca()
axes.set_xlim([xmin,xmax])
axes.set_ylim([ymin,ymax])设置纵坐标范围:
本帖最后由 马甲1号 于
14:30 编辑
原理和matlab差不多,用低阶函数手动设置label。
Figure对象全局参数设置from matplotlib import rcParams
# rcParams['axes.edgecolor']='white'
# rcParams['xtick...
他的最新文章
讲师:吴岸城
您举报文章:
举报原因:
原文地址:
原因补充:
(最多只允许输入30个字)最近在做相关数据自动化和处理分析,个人觉得python在这方面,配合一些数据分析和作图工具包(matplotlib, googlechart,pychart等等),实现自动化分析还是非常强大的,也很容易入门和上手,以自动化代替人手工去分析极大提升办事效率这也是一件非常有意义的事情
后面会陆陆续续将python自动化分析和画图方面的东东整理记录下来,这也是不断积累的过程,希望有所沉淀
【背景:基于python脚本做海量数据自动化分析时,基于数据画图分析成为一种更直观的方式,但当数据多时,坐标显示的刻度需要控制以使图形显示和分析更直观和清晰】
& & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & & &
&这幅数据x坐标显示的刻度有点问题,当数据越来越多时,若坐标主刻度间隔未得到合理控制,x坐标上数据显示会越来越乱,如图中红线圈点的数据。
按照matplotlib官方document中的用法,对 x axis/ y axis坐标刻度间隔的控制可以基于 matplotlib.ticker里的&MultipleLocator /FormatStrFormatter模块来控制,具体实现及其效果见下:
【matplotlib 关于坐标由axis的详细document 说明请参考 链接: 】
#!/usr/bin/env python#-*- coding: utf-8 -*- #---------------------------------------------------#演示MatPlotLib中设置坐标轴主刻度标签和次刻度标签.
#对于次刻度显示,如果要使用默认设置只要matplotlib.pyplot.minorticks_on()
#---------------------------------------------------
from pylab import *from matplotlib.ticker import &MultipleLocator
from matplotlib.ticker import &FormatStrFormatter
#---------------------------------------------------
&#将x主刻度标签设置为20的倍数(也即以 20为主刻度单位其余可类推)
xmajorLocator
= MultipleLocator(20);
#设置x轴标签文本的格式
xmajorFormatter = FormatStrFormatter('%3.1f')&
#将x轴次刻度标签设置为5的倍数xminorLocator
= MultipleLocator(5)&
#设定y 轴的主刻度间隔及相应的刻度间隔显示格式
#将y轴主刻度标签设置为1.0的倍数ymajorLocator
= MultipleLocator(1.0)&
&#设置y轴标签文本的格式ymajorFormatter = FormatStrFormatter('%1.1f')
#将此y轴次刻度标签设置为0.2的倍数yminorLocator
= MultipleLocator(0.2)&
t = arange(1.0, 100.0, 1)s=t*exp(-t*1.3)+2*sqrt(t)
&#注意:一般都在ax中设置,不再plot中设置
ax = subplot(111)plot(t,s,'--r*')
#设置主刻度标签的位置,标签文本的格式ax.xaxis.set_major_locator(xmajorLocator)ax.xaxis.set_major_formatter(xmajorFormatter)
ax.yaxis.set_major_locator(ymajorLocator)ax.yaxis.set_major_formatter(ymajorFormatter)
#显示次刻度标签的位置,没有标签文本ax.xaxis.set_minor_locator(xminorLocator)ax.yaxis.set_minor_locator(yminorLocator)
ax.xaxis.grid(True, which='major') #x坐标轴的网格使用主刻度ax.yaxis.grid(True, which='minor') #y坐标轴的网格使用次刻度
##########################################################
【附画出来的坐标图形格式效果】
&另附经过 添加主刻度单位和标识限制之后画出来的图形(x axis 这次清晰了很多:))
& & & & & & & & & & & & & & & & & & & &
阅读(...) 评论() &问题: python使用matplotlib画图,如何让横坐标值由大到小逆序显示?
描述:matplotlib横坐标值由大到小&&&&&在python中使用matplotlib画图,默认横坐标都是由小到大(1,2,3,4,5),但我现在项目特殊需求,想让横坐标值由大到小逆序显示(5,4,3,2,1),如何实现呢?
import&matplotlib.pyplot&as&plt
plt.figure()
ax1&=&plt.subplot(121)
ax2&=&plt.subplot(122)
xlist&=&[1,2,3,4,5]
ylist&=&[10,20,30,40,50]
plt.sca(ax1)
plt.title("Test&X&Label")&
plt.xlabel("X")
plt.ylabel("Y")
plot1,&=&plt.plot(xlist,ylist,'ro')
plt.show()解决方案1:import&matplotlib.pyplot&as&plt
plt.figure()
ax1&=&plt.subplot(121)
ax2&=&plt.subplot(122)
xlist&=&[1,2,3,4,5]
ylist&=&[10,20,30,40,50]
plt.sca(ax1)
plt.title("Test&X&Label")&
plt.xlabel("X")
plt.ylabel("Y")
plot1,&=&plt.plot(xlist,ylist,'ro')
plt.gca().invert_xaxis()&
plt.show()
以上介绍了“ python使用matplotlib画图,如何让横坐标值由大到小逆序显示?”的问题解答,希望对有需要的网友有所帮助。
本文网址链接:/itwd/4076352.html
上一篇: 下一篇:使用Matplotlib进行绘图时,当x轴的数据太多的时候,就需要设置x轴的刻度和显示文本,关键代码如下:
绘图结果如下:
阅读(...) 评论()

我要回帖

更多关于 matplotlib移动坐标轴 的文章

 

随机推荐