在python中使用plotnine 0.6.0绘制平面图时出现问题

2024-06-02 14:22:53 发布

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

我正在尝试使用python 3.7.4中的plotnine 0.6.0创建一个简单的绘图,其中线条根据因子变量着色

import pandas as pd
import plotnine as pn
import datetime

# data
df = pd.DataFrame(
{'name': ('Eric', 'Eric', 'Eric', 'Eric', 'Eric', 'Eric', 'Nico', 'Nico',
   'Nico', 'Nico', 'Nico', 'Nico', 'Sanne', 'Sanne', 'Sanne', 'Sanne',
   'Sanne', 'Sanne'),
 'date': (datetime.date(2013, 8, 15), datetime.date(2013, 8, 15),
   datetime.date(2013, 8, 15), datetime.date(2013, 8, 16),
   datetime.date(2013, 8, 16), datetime.date(2013, 8, 16),
   datetime.date(2013, 8, 15), datetime.date(2013, 8, 15),
   datetime.date(2013, 8, 15), datetime.date(2013, 8, 16),
   datetime.date(2013, 8, 16), datetime.date(2013, 8, 16),
   datetime.date(2013, 8, 15), datetime.date(2013, 8, 15),
   datetime.date(2013, 8, 15), datetime.date(2013, 8, 16),
   datetime.date(2013, 8, 16), datetime.date(2013, 8, 16)),
 'altitude': ( 71,  68,  68,  92,  95, 104, 382, 197, 206, 157, 156, 157,  55,
    54,  55,  65,  62,  73)
 })

# summarize the data by date
summ = df.groupby(['name', 'date']).altitude.mean().reset_index(name = 'altitude')

# plot the data by "name"
pn.ggplot(mapping = pn.aes(x = 'date',
                      y = 'altitude',
                      color = 'name'),
     data = summ) +\
pn.geom_line()

这段代码创建了我期望的背景: enter image description here

但是抛出了一个错误:

C:\Anaconda3\lib\site-packages\plotnine\geoms\geom_path.py:83: 
PlotnineWarning: geom_path: Each group consist of only one observation. 
Do you need to adjust the group aesthetic?
"group aesthetic?", PlotnineWarning)

如果我删除颜色方面

pn.ggplot(mapping = pn.aes(x = 'date',
                      y = 'altitude'),
     data = summ) +\
pn.geom_line()

我得到:

enter image description here

我知道我的问题与this有关,但我不想要一行。我希望每个name都有不同的行


Tags: thenameimportdatadatetimedategroupnico
1条回答
网友
1楼 · 发布于 2024-06-02 14:22:53

好吧,在我浪费了几个小时的时间里,我偶然发现了解决方案:我必须同时指定color分组变量group分组变量。(注意:在R中使用ggplot2时,这不是必需的,但在plotnine中显然是必需的。)

pn.ggplot(mapping = pn.aes(x = 'date',
                      y = 'altitude',
                      color='name',
                      group='name'),
     data = summ) +\
pn.geom_line()

enter image description here

相关问题 更多 >