【问题标题】:matplotlib uppercase tick labelsmatplotlib 大写刻度标签
【发布时间】:2018-03-21 03:03:18
【问题描述】:

我正在尝试通过像这样 (plot code) 添加带有 %^b 标志的模式,将 matplotlib (2.1.0) (Python 3.6.3 | Windows 10) 中的 x 轴刻度标签设置为大写:

ax.xaxis.set_minor_formatter(mdates.DateFormatter('%^b'))

但是我得到了错误

ValueError: Invalid format string

%b 我得到了没有任何错误的情节:

另外,我想删除第一个和最后一个刻度标签以避免重复。

我想知道你是否知道我的问题的任何解决方法。

【问题讨论】:

  • 请提供一个最小的工作示例,并附上一些代码。 IE。一些理想化的情节,其中仅包含您真正感兴趣的那些功能。请参阅:stackoverflow.com/help/mcve

标签: python matplotlib strftime


【解决方案1】:

在 python 中,字符串通过str.upper() 转换为大写。您可以通过matplotlib.ticker.FuncFormatter 将此应用于通过DateFormatter 生成的标签

fmt= lambda x,pos: mdates.DateFormatter('%b')(x,pos).upper()
ax.xaxis.set_major_formatter(ticker.FuncFormatter(fmt))

完整示例:

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

x = pd.date_range("2001-01-01", "2001-12-31", freq="5D")
y = np.random.rand(len(x))

fig, ax=plt.subplots()
ax.plot(x,y)

ax.xaxis.set_major_locator(mdates.MonthLocator())
fmt= lambda x,pos: mdates.DateFormatter('%b')(x,pos).upper()
ax.xaxis.set_major_formatter(ticker.FuncFormatter(fmt))

plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 2014-08-03
    • 2017-01-07
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多