首页 > 解决方案 > 使用循环绘制 n 个图表并变量标题 Python

问题描述

我有一组数据(Excel),我使用 pandas 数据框将其加载到 python 中。我想要做的是创建一个循环,它将每隔一列打印一个图,用于在一定限制内的所有元素。我的数据位于以这种方式构造的 excel 文件中:

索引 | 日期 | W300 | W301 | W303 | 温恩 |

我只想打印强标记的列,总而言之,第二列(n + 2)。

到目前为止,这就是我的代码:

import pandas as pd  
import seaborn as sns
import matplotlib.pyplot as plt 

data = pd.read_excel(r'C:\Users\marco\Desktop\HZ.xlsx', skiprows=0, sheet_name='Heizzonen')
gapminder = pd.DataFrame(data, columns= 
['W300','W301','W302','W303','W304','W305','W306','W307','W308','W309','W310',.............,'W800']

gapminder2=gapminder['W304'].iloc[25663:30703] 

hplot = sns.histplot(gapminder2, kde=False, color='blue', bins=100)
plt.title('W300', fontsize=18)
plt.xlabel('Temperatur [°C]', fontsize=16)
plt.ylabel('Häufigkeit', fontsize=16)

我想绘制 n 图表,对于每个图表,我想使用变量在标题中标记它们。这样循环就针对列和标题。我会提供我的想法,但我不知道。

标签: pythonpandasmatplotlib

解决方案


表达式gapminder.columns.to_list()将为您提供列名列表。使用[0::2](对于偶数元素)或[1::2](对于奇数元素)可以获得该列表的每个第二个元素:

for col in gapminder.columns.to_list()[1::2]:
  column = gapminder[col]
  # here comes your logic

推荐阅读