【问题标题】:Matplotlib: How to make a plot using FOR loopMatplotlib:如何使用 FOR 循环制作绘图
【发布时间】:2021-05-23 01:45:04
【问题描述】:

我正在尝试使用 .iterrows() 进行绘图

for index, rows in df.iterrows():
    if rows['Country'] == 'France' and rows['Confirmed'] != 0:
        plt.plot(rows['Date'], rows['Confirmed'])

结果我得到一个空的情节。 我错过了什么?

我做的时候有一些数据:

df.loc[df['Country'] == 'France'].tail(2)

enter image description here

【问题讨论】:

  • 嗨@artyom-p。请提供一些我们可以轻松复制的示例数据。另外,请描述您想要的预期输出;是条形图吗?折线图?我根据我的理解添加了我的答案。如果这不是您需要的,请提供我提到的更多详细信息。

标签: python pandas matplotlib plot data-visualization


【解决方案1】:

如果我理解正确,您想绘制“已确认”列随时间变化的条形图,但仅限于法国。
如果是这种情况,那么您不需要使用 For 循环。 Pandas 和 Matplotlib 都支持对 Series 和列表的操作。

做你需要的一种方法是:

# First, create a new dataframe that contains data of "France" and "Confirmed" > 0
france_confirmed_df = df[(df['Country'] == 'France') & (df['Confirmed'] != 0)]
# Then plot the bar plot using that new dataframe
plt.bar(france_confirmed_df['Date'], france_confirmed_df['Confirmed'])

我建议你看看10 minutes to pandasMatplotlib's Pyplot tutorial

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-04
    • 2018-09-06
    • 2020-05-06
    相关资源
    最近更新 更多