如何在Python matplotlib中订购月份?

2024-10-03 19:20:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个基于SQL中月份名称的表。以monthnumbers int排序。我想用matplotlib在Python Jupyter笔记本中生成一个线图。但是线图给了我字母顺序(a,b,c等等…)

这是不对的。我需要订单的月份号。在

我该怎么做? 我在select语句中同时有monthnumber和monthname:

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()

Tags: inforsqlpltcursorintrow月份
1条回答
网友
1楼 · 发布于 2024-10-03 19:20:35

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

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

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()

enter image description here

相关问题 更多 >