【问题标题】:How to order months in Python matplotlib?如何在 Python matplotlib 中订购月份?
【发布时间】:2017-11-13 12:29:44
【问题描述】:

我有一个基于 SQL 中月份名称的表。用 monthnumbers int 排序。我想用 matplotlib 在 Python Jupyter Notebook 中制作折线图。但是折线图给了我一个字母顺序(a、b、c 等...)

这是不正确的。我需要月份数字的订单。

我该怎么做? 我的选择语句中同时包含月份编号和月份名称:

cursor = conx.cursor()
cursor.execute(sql)
Revenue = []
Monthnumber = [] 
Month = []
Maandnummer = []

for row in cursor:
    regio.append(str(row.Mond))
    Revenue.append(int(row.Revenue))
    Month.append(int(row.Month))
    Maandnummer.append(int(row.Monthnumber))

df = pd.read_sql(sql, conx)    
Months = ['januari','februari','maart','april', 'mei', 'juni', 'juli', 'augustus','september', 'oktober', 'november', 'december']
mapping = {Maandnummer: i for i, maandnummer in enumerate(Months)}
key = df['maandnummer'].map(mapping)

# Plot de inhoud van het dataframe (tabel als resultaat van query)
plt.figure(figsize=(20,10))
aantal.sort()
plt.plot(key, omzet, 'ro')
plt.ylabel('Omzet')
plt.xlabel('Regio')
plt.show()

【问题讨论】:

  • 如果你不分享,很难帮助你理解你在谷歌搜索时找到的解决方案。
  • 月 = ['januari','februari','maart','april', 'mei', 'juni', 'juli', 'augustus','september', 'oktober' , 'november', 'december'] mapping = {maandnum: i for i, maandnum in enumerate(Months)} key = df['maandnum'].map(mapping)

标签: python sql matplotlib


【解决方案1】:

我在不同的列表和列之间迷路了,其中一些似乎包含相同的内容。所以这是一个最小的例子。

这个想法确实是根据它在列表中的位置将月份映射到一个数字。这可以使用字典来完成:dict(zip(Months,range(len(Months)))).
然后可以将此映射应用于数据框列。原则上这是问题中代码的方法,但虽然它不可重现,但以下是。

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

Months = ['januari','februari','maart','april', 'mei', 'juni', 'juli', 
          'augustus','september', 'oktober', 'november', 'december']

df = pd.DataFrame({"maand" : np.random.choice(Months, size=100),
                   "omzet" : np.random.binomial(100,0.5, size=100)})
mapping = dict(zip(Months,range(len(Months))))
df['maandnummer'] = df['maand'].map(mapping)


plt.figure()

plt.plot(df['maandnummer'], df["omzet"], 'ro')
plt.xticks(range(len(Months)),Months, rotation=45,ha="right")
plt.ylabel('Omzet')
plt.xlabel('Maand')
plt.show()

【讨论】:

    猜你喜欢
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    • 1970-01-01
    • 2018-03-04
    相关资源
    最近更新 更多