【问题标题】:For loop for charting in Python用于在 Python 中绘制图表的 For 循环
【发布时间】:2021-04-15 18:32:54
【问题描述】:

我想创建一个带有 for 循环的图表。 X 轴绘制正确,甚至 y 轴刻度设置正确,但没有创建实际的折线图。 下面的代码可能有什么问题?

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib

test = {'date':[2012, 2013, 2014, 2015],'val':[9,15,12,20]}

test_df=pd.DataFrame(data=test)

test_df=test_df.set_index('date')

fig, ax = plt.subplots(figsize=(25,25))

for i in range(0, len(test_df)):
    
    ax.plot(test_df.index[i], test_df['val'].iloc[i], color='blue', linewidth=10)
        
plt.show()

【问题讨论】:

    标签: python pandas dataframe for-loop matplotlib


    【解决方案1】:

    你不要给出坐标来绘制一条导致我们绘制散点图的线。

    for i in range(0, len(test_df)): 
        ax.scatter(test_df.index[i], test_df['val'].iloc[i], color='blue', linewidth=10)
    

    就我而言,这将解决您的问题,但如果您真的想连接这些点,那么您可以在没有 for 循环的情况下试一试:

    ax.plot(test_df.index, test_df['val'], color='blue', linewidth=10)
    

    【讨论】:

      【解决方案2】:

      您可以使用以下方式绘制整个系列:

      ax.plot(test_df.index, test_df['val'], color='blue', linewidth=10)
      

      并且没有for循环

      或者自己绘制点:

      ax.plot(test_df.index[i], test_df['val'].iloc[i], "b+", linewidth=10)
      

      请参阅 matplotlib's markers 了解各个点标记

      【讨论】:

      • 谢谢,这解决了我的问题! "b+" 本身不起作用,但其他标记起作用。
      猜你喜欢
      • 2016-07-14
      • 1970-01-01
      • 1970-01-01
      • 2018-04-24
      • 2021-08-02
      • 2021-08-11
      • 2015-07-24
      • 2020-07-24
      • 2016-09-29
      相关资源
      最近更新 更多