【问题标题】:Order months correctly in plot - Python pandas matplotlib在情节中正确订购月份 - Python pandas matplotlib
【发布时间】:2021-02-15 00:57:24
【问题描述】:

我在这个论坛上看到了这个问题解决方案的不同方法,但我无法在我的代码中实现它。我需要对 x 轴进行更正以便您知道:1 月、2 月、3 月、4 月、5 月等。我更改了数字(因为我收到了 319000 行的大数据框,并且在 DF 列中的“月份”看起来像Month = [1,2,3,4,5,6,7,8,9,10,11,12]) 列的“月份”到月份的名称,通过导入日历并使用“apply(lambda x:. ..",你怎么看。我知道这可能是一个非常新手的问题,但如果有人可以帮助我,我将不胜感激。

代码:

wykres = MojaBaza['Month'].astype(int).apply(lambda x: calendar.month_abbr[x]).value_counts().sort_values(ascending=True).plot(kind='bar', figsize=(8,8),
title="Amount of the crimes in Boston during the months in years 2015-2018 ")

    wykres.set_xticklabels(wykres.get_xticklabels(), rotation=40, ha="right")
    plt.tight_layout()
    plt.show()

【问题讨论】:

  • 大概.sort_values(ascending=True) 是您的问题 - 我假设这是按您正在绘制的列中的计数对数据框进行排序(即 y 轴 - 这就是条形高度从左侧上升的原因向右)。尝试删除它,它们应该是原始顺序
  • 如果我删除.sort_values(ascending=True),那么我从右到左升序,所以几乎相同。我需要一月第一在左边,十二月最后在右边。感谢您的快速响应。

标签: python pandas matplotlib


【解决方案1】:

我没有数据,所以我创建了示例数据并创建了代码。我创建了月份名称列表,将日历中的聚合值转换为主要数据框,然后使用月份名称列表更新索引。

import pandas as pd
import numpy as np
import datetime
import calendar

date_rng = pd.date_range('2015-01-01', '2019-01-01', freq='1D')
val = np.random.randint(5,50,(1462,))

MojaBaza = pd.DataFrame({'date':pd.to_datetime(date_rng), 'value':val})

MojaBaza['Month'] = MojaBaza['date'].dt.month
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
temp = MojaBaza['Month'].astype(int).apply(lambda x: calendar.month_abbr[x]).value_counts().reset_index()
temp.set_index('index', inplace=True)
temp = temp.reindex(index=months)
wykres = temp.plot(kind='bar', figsize=(8,8), title="Amount of the crimes in Boston during the months in years 2015-2018 ")

【讨论】:

  • 感谢我在我的代码中实现了这个并且它正在工作:)
猜你喜欢
  • 1970-01-01
  • 2019-01-14
  • 2021-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多