我一直在尝试使用plotnine绘制堆积的条形图。此图表示同一“类别”下的月末库存。 “ SubCategory”其应堆叠的内容。
我已经从查询到数据库建立了一个熊猫数据框。该查询检索日期范围内“类别”内每个“子类别”的总和。
这是DataFrame的格式:
SubCategory1 SubCategory2 SubCategory3 .... Dates
0 1450.0 130.5 430.2 .... 2019/Jan
1 1233.2 1000.0 13.6 .... 2019/Feb
2 1150.8 567.2 200.3 .... 2019/Mar
日期应位于X轴上,Y应由“ SubCategory1” +“ SubCategory2” +“ SubCategory3”之和确定,并且颜色可区分。
我尝试这样做是因为我认为这很有意义,但是没有运气:
g = ggplot(df)
for key in subcategories:
g = g + geom_bar(aes(x='Dates', y=key), stat='identity', position='stack')
其中子类别是带有SubCategories名称的字典。
也许数据框的格式不理想。或者我不知道如何将其与plotnine / ggplot一起正确使用。
感谢您的帮助。
答案 0 :(得分:1)
答案 1 :(得分:1)
您需要整齐的数据
from io import StringIO
import pandas as pd
from plotnine import *
from mizani.breaks import date_breaks
io = StringIO("""
SubCategory1 SubCategory2 SubCategory3 Dates
1450.0 130.5 430.2 2019/Jan
1233.2 1000.0 13.6 2019/Feb
1150.8 567.2 200.3 2019/Mar
""")
data = pd.read_csv(io, sep='\s+', parse_dates=[3])
# Make the data tidy
df = pd.melt(data, id_vars=['Dates'], var_name='categories')
"""
Dates categories value
0 2019-01-01 SubCategory1 1450.0
1 2019-02-01 SubCategory1 1233.2
2 2019-03-01 SubCategory1 1150.8
3 2019-01-01 SubCategory2 130.5
4 2019-02-01 SubCategory2 1000.0
5 2019-03-01 SubCategory2 567.2
6 2019-01-01 SubCategory3 430.2
7 2019-02-01 SubCategory3 13.6
8 2019-03-01 SubCategory3 200.3
"""
(ggplot(df, aes('Dates', 'value', fill='categories'))
+ geom_col()
+ scale_x_datetime(breaks=date_breaks('1 month'))
)