python - 在循环中绘制 DataFrameGroupBy 对象会给出多个图
问题描述
继上一个问题之后,我对 matplotlib.pyplot 的工作方式感到困惑。我有一个包含多个组的 DataFrameGroupBy 对象,我想制作一个具有多个功能(每组一个)的图形。我的研究表明,以下代码基本上应该产生一个多行的图形:
import pandas as pd
import matplotlib.pyplot as plt
with open("data.csv", encoding='utf-8') as datei:
df = pd.read_csv(datei, sep=';')
groups = df.groupby(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q']) # Columns from A-Q are distinctive as a unit
for element, group in groups: # Looping over the GroupBy objects
group.plot(x='R', y='X') # Columns R and X contain the x- and y-axis values respectively
# According to SO answers, calling .plot() should not create a graph until the graph itself is called
plt.show()
相反,我得到了多个图表,每个图表都有一条线。按照一些说明,我尝试在我能想到的所有可能的地方推动plt.ion()
,plt.ioff()
和plt.pause(0.5)
,但我不太明白它们是如何工作的,所以我可能没有正确完成。
解决方案
您正在使用 pandas 的绘图功能。您可以通过使用 传递对轴的引用来指示此函数使用哪些轴ax=
。
import pandas as pd
import matplotlib.pyplot as plt
with open("data.csv", encoding='utf-8') as datei:
df = pd.read_csv(datei, sep=';')
groups = df.groupby(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q']) # Columns from A-Q are distinctive as a unit
fig, ax = plt.subplots() # creates one figure with one axes
for element, group in groups: # Looping over the GroupBy objects
group.plot(x='R', y='X', ax=ax) # Columns R and X contain the x- and y-axis values respectively
# According to SO answers, calling .plot() should not create a graph until the graph itself is called
plt.show()
推荐阅读
- sql - 具有多个值的 WHERE IN 子句
- sql - 带有 XSLT 标头的 SQL Server FOR XML 查询
- comments - 如何在 Swift 4 中将表格添加到文档注释?
- php - php结合重定向和刷新
- javascript - 根据字符串值为项目分配不同的颜色
- python - 如何在 Django 2.1 中实现新帖子的审核
- jdbc - 如何使我的 pyspark 数据库在 Windows 上直线可见?
- database - 订单行导入不识别产品外部 ID?
- php - 我可以在 cpanel 中看到插件,但在 wordpress 仪表板中看不到它
- r - 手动将置信区间添加到条形图