簡體   English   中英

Python和Matplotlib:減少x刻度線的數量並刪除零填充

[英]Python and Matplotlib: reduce number of x tick marks and remove zero-padding

我是matplotlib和pyplot的新手,並試圖繪制一個大型數據集。 以下是一個小片段。

情節有效,但xtick標記很擁擠。

如何減少刻度線的數量?

使用plt.locator_params(nbins=4)返回錯誤:

AttributeError: 'FixedLocator' object has no attribute 'set_params'

有沒有辦法從pyplot中的日期標簽中刪除0填充?

import matplotlib.pyplot as plt


x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
xticks = ['01/01', '01/02', '01/03', '01/04', '01/05', '01/06', '01/07', '01/08', '01/09', '01/10', '01/11', '01/12', '01/13', '01/14', '01/15', '01/16', '01/17', '01/18', '01/19', '01/20', '01/21', '01/22', '01/23', '01/24', '01/25', '01/26', '01/27', '01/28', '01/29', '01/30']
y = [80, 80, 60, 30, 90, 50, 200, 300, 200, 150, 10, 80, 20, 30, 40, 150, 160, 170, 180, 190, 20, 210, 220, 20, 20, 20, 200, 270, 280, 90, 00]
y2 = [100, 100, 200, 300, 40, 50, 60, 70, 80, 90, 100, 110, 12, 13, 10, 110, 16, 170, 80, 90, 20, 89, 28, 20, 20, 28, 60, 70, 80, 90, 30]


plt.plot(x, y)
plt.plot(x, y2)
plt.xticks(x, xticks, rotation=90)
plt.show()

在此輸入圖像描述

由於matplotlib有一些非常好的日期工具,我認為將日期字符串轉換為datetime.datetime對象是有意義的。

然后你可以使用其中一個方便的日期定位器; 在這種情況下, DayLocator最有意義。 要使用跳過某些標簽,請使用interval kwarg。

然后從xticklabels中刪除前導零,您需要一個自定義格式化功能。

import datetime as dt

import matplotlib.pyplot as plt
import matplotlib.dates as mdates 
import matplotlib.ticker as tkr

def xfmt(x,pos=None):
    ''' custom date formatting '''
    x = mdates.num2date(x)
    label = x.strftime('%m/%d')
    label = label.lstrip('0')
    return label

x = ['01/01', '01/02', '01/03', '01/04', '01/05', '01/06', '01/07', '01/08', '01/09', '01/10', '01/11', '01/12', '01/13', '01/14', '01/15', '01/16', '01/17', '01/18', '01/19', '01/20', '01/21', '01/22', '01/23', '01/24', '01/25', '01/26', '01/27', '01/28', '01/29', '01/30', '01/31']
xdates = [dt.datetime.strptime(i,'%m/%d') for i in x]
y = [80, 80, 60, 30, 90, 50, 200, 300, 200, 150, 10, 80, 20, 30, 40, 150, 160, 170, 180, 190, 20, 210, 220, 20, 20, 20, 200, 270, 280, 90, 00]
y2 = [100, 100, 200, 300, 40, 50, 60, 70, 80, 90, 100, 110, 12, 13, 10, 110, 16, 170, 80, 90, 20, 89, 28, 20, 20, 28, 60, 70, 80, 90, 30]

plt.plot(xdates,y)
plt.plot(xdates,y2)
plt.setp(plt.gca().xaxis.get_majorticklabels(),rotation=90)
plt.gca().xaxis.set_major_formatter(tkr.FuncFormatter(xfmt))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=4))
plt.gca().xaxis.set_minor_locator(mdates.DayLocator())
plt.show()

上面的代碼生成以下圖:

_sompl.png

你使用maxNLocator

fig, ax = plt.subplots()
locator = MaxNLocator(nbins=3) # with 3 bins you will have 4 ticks
ax.xaxis.set_major_locator(locator)

或者請參閱https://stackoverflow.com/a/13418954/541038

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM