如何在Python matplotlib中订购数月? [英] How to order months in Python matplotlib?

查看:41
本文介绍了如何在Python matplotlib中订购数月?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a table based on month names in SQL. sorted with the monthnumbers int. I want to make a line graph in Python Jupyter Notebook with matplotlib. BUT the line graph is giving me an alphabatical order ( a, b, c etc...)

这是不正确的.我需要以月份为单位的订单.

This is not correct. I need the order in month numbers.

我该怎么做?我的选择语句中既有月号又有月名:

How can i do this? i have both the monthnumber and the monthname in my select statement:

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

推荐答案

我迷失在不同的列表和列之间,其中一些似乎包含相同的内容.因此,这是一个最小的示例.

I got lost between the different lists and columns, where some seem to include the same content. So here is a minimal example.

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

The idea is indeed to map the month to a number according to its position in the list. This can be done using a dictionary: dict(zip(Months,range(len(Months)))).
One may then apply this map to the dataframe column. In principle that is the approach from the code in the question, but while it is not reproducible, the following would be.

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

这篇关于如何在Python matplotlib中订购数月?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆