Matplotlib:如何增加刻度线之间的空间(或减少刻度线的数量)? [英] Matplotlib: How to increase space between tickmarks (or reduce number of tickmarks)?

查看:46
本文介绍了Matplotlib:如何增加刻度线之间的空间(或减少刻度线的数量)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何像下面的图所示那样增加刻度线之间的间隔?

情节 1:设置

数据集

时间值2010-01 12010-02 22010-03 32010-04 42010-05 52010-06 62010-07 72010-08 82010-09 92010-10 82011-01 72011-02 62011-03 52011-04 42011-05 32011-06 22011-07 12011-08 22011-09 32011-10 42011-11 52011-21 6


我尝试过的事情:

在帖子

但如您所见,刻度线保持不变.

因此,使用该设置,我天真地尝试用 ax.get_xticks()替换 ax.xaxis.get_ticklabels()部分,但到目前为止没有成功:

# in:对于 n,在 enumerate(ax.get_xticks()) 中打勾:如果n%every_nth!= 0:tick.set_visible(假)#out:AttributeError:'int'对象没有属性'set_visible'

ax.tick_params? 中似乎也没有选项.你甚至会在那里找到填充,但没有关于刻度间距.

任何其他建议都会很棒!通常我会将索引更改为 PeriodIndex 并使用 import matplotlib.dates as mdates 来格式化轴,但我真的很喜欢这种更直接的技术.

以下是简单复制和粘贴的全部内容:

#imports导入matplotlib.pyplot作为plt将熊猫作为pd导入将numpy导入为np# df = pd.read_clipboard(sep='\\s+')# 绘图设置无花果,ax = plt.subplots()ax.plot(df['time'], df['value'])plt.xticks(旋转=45)#尝试1每个_nth = 5对于n,在枚举中标记(ax.xaxis.get_ticklabels()):如果 n % every_nth != 0:#打印(n)label.set_visible(False)#every_nth = 5#对于n,在枚举(ax.xaxis.get_ticks())中打勾:# 如果 n % every_nth != 0:# #打印(n)#tick.set_visible(False)plt.show()

解决方案

节拍间距由后续节拍位置的差异严格确定.Matplotlib 通常会自动为您找到合适的刻度位置.

 将matplotlib.pyplot导入为plt将熊猫作为pd导入将numpy导入为npdf = pd.DataFrame({"time":np.arange("2010-01-01","2012-01-01",dtype ="datetime64 [M]"),值":np.random.randint(0,10,size = 24)})无花果,ax = plt.subplots()ax.plot(df['time'], df['value'])plt.setp(ax.get_xticklabels(),旋转= 45,ha ="right")plt.show()

如果你不喜欢那些你可以通过自动收报机提供定制的.

 将matplotlib.pyplot导入为plt导入 matplotlib.dates 作为 mdates将熊猫作为pd导入将numpy导入为npdf = pd.DataFrame({"time" : np.arange("2010-01-01", "2012-01-01", dtype="datetime64[M]"),值":np.random.randint(0,10,size=24)})无花果,ax = plt.subplots()ax.plot(df ['time'],df ['value'])ax.xaxis.set_major_locator(mdates.MonthLocator((1,7)))ax.xaxis.set_major_formatter(mdates.DateFormatter(%Y-%b"))plt.setp(ax.get_xticklabels(), rotation=45, ha="right")plt.show()

如果你真的希望你的日期是分类的,你可以使用 MultipleLocator.例如.在第5个类别上打勾,

 将matplotlib.pyplot导入为plt导入 matplotlib.ticker 作为 mticker将熊猫作为pd导入将numpy导入为npdf = pd.DataFrame({"time":np.arange("2010-01-01","2012-01-01",dtype ="datetime64 [M]"),值":np.random.randint(0,10,size = 24)})df ["time"] = df ["time"].dt.strftime('%Y-%m')无花果,ax = plt.subplots()ax.plot(df ['time'],df ['value'])ax.xaxis.set_major_locator(mticker.MultipleLocator(5))plt.setp(ax.get_xticklabels(),旋转= 45,ha ="right")plt.show()

How do you increase the spacing between the tickmarks like in the plot below?

Plot 1: Setup

Dataset

time value
2010-01 1
2010-02 2
2010-03 3
2010-04 4
2010-05 5
2010-06 6 
2010-07 7
2010-08 8
2010-09 9
2010-10 8
2011-01 7
2011-02 6
2011-03 5
2011-04 4
2011-05 3
2011-06 2
2011-07 1
2011-08 2
2011-09 3
2011-10 4
2011-11 5
2011-21 6


What I've tried:

In the post How to: reduce number of ticks with matplotlib, a user shows how to increase space between tick labels like this:

# Attempt 1
every_nth = 5
for n, label in enumerate(ax.xaxis.get_ticklabels()):
    if n % every_nth != 0:
        #print(n)
        label.set_visible(False)

Plot 2: An attempt

But as you can see, the tickmarks remain untouched.

So using that setup, I naively tried replacing the ax.xaxis.get_ticklabels() part with ax.get_xticks(), but with no success so far:

# in:
for n, tick in enumerate(ax.get_xticks()):
    if n % every_nth != 0:
        tick.set_visible(False)

# out: AttributeError: 'int' object has no attribute 'set_visible'

And there does not seem to be an option in the ax.tick_params? either. You'll even find padding there, but nothing about tick spacing.

Any other suggestions would be great! Normally I'd change the index to PeriodIndex and format the axis using import matplotlib.dates as mdates, but I'd really like a more straight-forward technique for this one.

Here's the whole thing for an easy copy&paste:

#imports
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# df = pd.read_clipboard(sep='\\s+')

# plot setup
fig, ax = plt.subplots()
ax.plot(df['time'], df['value'])
plt.xticks(rotation=45)

# Attempt 1
every_nth = 5
for n, label in enumerate(ax.xaxis.get_ticklabels()):
    if n % every_nth != 0:
        #print(n)
        label.set_visible(False)

#every_nth = 5
#for n, tick in enumerate(ax.xaxis.get_ticks()):
#    if n % every_nth != 0:
#        #print(n)
#        tick.set_visible(False)

plt.show()

解决方案

The tickspacing is solemnly determined by the difference of subsequent tick locations. Matplotlib will usually find nice tick locations for you automatically.

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df = pd.DataFrame({"time" : np.arange("2010-01-01", "2012-01-01", dtype="datetime64[M]"),
                   "value" : np.random.randint(0,10,size=24)})
fig, ax = plt.subplots()
ax.plot(df['time'], df['value'])
plt.setp(ax.get_xticklabels(), rotation=45, ha="right")

plt.show()

If you don't like those you may supply custom ones, via a ticker.

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
import numpy as np

df = pd.DataFrame({"time" : np.arange("2010-01-01", "2012-01-01", dtype="datetime64[M]"),
                   "value" : np.random.randint(0,10,size=24)})
fig, ax = plt.subplots()
ax.plot(df['time'], df['value'])
ax.xaxis.set_major_locator(mdates.MonthLocator((1,7)))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%b"))
plt.setp(ax.get_xticklabels(), rotation=45, ha="right")

plt.show()

If you really want your dates to be categorical, you may use a MultipleLocator. E.g. to tick every 5th category,

import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import pandas as pd
import numpy as np

df = pd.DataFrame({"time" : np.arange("2010-01-01", "2012-01-01", dtype="datetime64[M]"),
                   "value" : np.random.randint(0,10,size=24)})
df["time"] = df["time"].dt.strftime('%Y-%m')

fig, ax = plt.subplots()
ax.plot(df['time'], df['value'])
ax.xaxis.set_major_locator(mticker.MultipleLocator(5))
plt.setp(ax.get_xticklabels(), rotation=45, ha="right")

plt.show()

这篇关于Matplotlib:如何增加刻度线之间的空间(或减少刻度线的数量)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆