【问题标题】:How to correctly use a for loop for plotting multiple lines from a csv in python?如何正确使用for循环在python中从csv中绘制多行?
【发布时间】:2020-07-24 06:14:59
【问题描述】:

我正在学习 Python(即将出现基本问题),并且我有很多数据来自一些分析,它们是如下所示的 CSV 文件:

我正在尝试重新创建下面的图(目前我在 Excel 中做这样的事情,随着数据量和可视化的复杂性,我想让事情变得更有效率。

我尝试使用 For 循环的概念为该列中的每个不同的“SectionName”绘制一条线,但显然遗漏了一些东西。

#read CSV
df=pd.read_csv('/Users/F/Documents/Data/LinesLoopTest.csv')

#Make Variables from dataframe columns
Value = df['Value']
Position = df['Xposition']
Section = df['SectionName']

#Setup Figure
fig = plt.figure(figsize=(6,3))
ax1 = fig.add_subplot(1,1,1)
ax1.set_title('Sections')
ax1.set_xlabel("XPosition")
ax1.set_ylabel("Value")

#plot lines by SectionName
for name in ['A', 'B', 'C']:
    plt.plot(Position, Value)

plt.show()

我意识到这是一个简单的问题,到目前为止我还没有找到一个解释,我可以真正理解这个过程,以至于我可以重新创建它然后在它的基础上进行构建。

【问题讨论】:

标签: python for-loop matplotlib plot


【解决方案1】:

您可以在SectionName 上使用groupby,然后绘制组

fig, ax = plt.subplots()

for section, group in df.groupby('SectionName'):
    group.plot(x='Xposition', y='Value', ax=ax, label=section)

【讨论】:

  • 嗨@sheldore,如果我想将每一行放在每个单独的图中,正确的做法应该是什么?
【解决方案2】:

我来晚了,所以我做了一个几乎“复制/粘贴”Sheldore 答案的版本(如果我得到批准他的答案)

import pandas as pd
import matplotlib.pyplot as plt 

# intialise data of lists. 
data = {'SectionName':['A','A','A', 'B','B','B', 'C','C','C'], 
        'Xpos':[1, 2, 3, 1, 2, 3, 1, 2, 3], 
        'Val':[0.2, 0.4, 0.5, 0.4, 1.3, 0.2, 1.2, 1.9, 1.8]} 

# Create DataFrame 
df = pd.DataFrame(data) 

fig, ax = plt.subplots()

for section, group in df.groupby('SectionName'):
    group.plot(x='Xpos', y='Val', ax=ax, label=section)
plt.show()

【讨论】:

  • @Sheldore 和 Ivan(所以只允许我称呼一个人),这正是我所需要的,谢谢!我看到你在用 groupby 做什么,太棒了!出于兴趣(这可能需要是一个单独的问题)有没有办法添加另一行,即所有“SectionNames”的平均行。我总是可以提出一个新问题。不管怎样,谢谢你的帮助!
猜你喜欢
  • 2021-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
相关资源
最近更新 更多