【问题标题】:Best way of showing dates in a Bar plot with Pandas使用 Pandas 在条形图中显示日期的最佳方式
【发布时间】:2019-01-30 16:42:46
【问题描述】:

我创建了一个这样的条形图:

但由于每个 x 轴标签都是 1 月的某一天(例如 1、3、4、5、7、8 等),我认为显示这一点的最佳方式是

__________________________________________________  x axis
Jan   1   3   4   5   7   8  ...
2019

但我不知道如何用 Pandas 做到这一点。

这是我的代码:

import pandas as pd
import matplotlib.plt as plt    

df = pd.read_excel('solved.xlsx', sheetname="Jan")

fig, ax = plt.subplots()

df_plot=df.plot(x='Date', y=['Solved', 'POT'], ax=ax, kind='bar', 
        width=0.9, color=('#ffc114','#0098c9'), label=('Solved','POT'))


def line_format(label):
"""
Convert time label to the format of pandas line plot
"""
month = label.month_name()[:3]
if month == 'Jan':
    month += f'\n{label.year}'
return month

ax.set_xticklabels(map(lambda x: line_format(x), df.Date))   

该功能是此处提供的解决方案:Pandas bar plot changes date format

我不知道如何修改它以获得我想要的轴

我的数据示例已解决.xlsx:

Date       Q    A    B  Solved POT
2019-01-04 Q4   11   9    14    5 
2019-01-05 Q4   9    11   14    5  
2019-01-08 Q4   11   18   10    6 
2019-01-09 Q4   18   19   18    5

【问题讨论】:

  • 你能提供样本数据吗?
  • 我已经编辑了我的问题
  • 我认为您正在寻找类似thisthis 的内容。现在,确切的解决方案不适用于 pandas 条形图(这是分类的),但它可以传达这个想法。
  • 嗨@ImportanceOfBeingErnest,我试过这两个都没有成功
  • 是的,它们旨在让您作为了解问题并自己找到解决方案的起点。

标签: pandas date matplotlib


【解决方案1】:

我找到了解决办法:

import pandas as pd
import matplotlib.plt as plt    

df = pd.read_excel('solved.xlsx', sheetname="Jan")

fig, ax = plt.subplots()

df_plot=df.plot(x='Date', y=['Solved', 'POT'], ax=ax, kind='bar', 
        width=0.9, color=('#ffc114','#0098c9'), label=('Solved','POT'))


def line_format(label):
"""
Convert time label to the format of pandas line plot
"""
day = label.day
if day == 2:
    day = str(day) + f'\n{label.month_name()[:3]}'
return day

ax.set_xticklabels(map(lambda x: line_format(x), df.Date)) 

plt.show()

在我的特殊情况下,我没有日期 2019-01-01 。所以对我来说第一天是 1 月 2 日

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 2015-07-19
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    • 2010-11-15
    相关资源
    最近更新 更多