【问题标题】:How to change what the axis of a plot is based on? (Python, Matplotlib)如何更改绘图轴的基础? (Python,Matplotlib)
【发布时间】:2020-12-15 15:15:18
【问题描述】:

我想创建一个 2 * 高度(即索引中的米值)与时间平方(即列中的十进制值)的关系图。我该怎么做呢? (在 matplotlib 中)

为清楚起见,我希望 y 轴为 2 * 索引值,x 轴为列内的时间平方。我希望这是一系列折线图

它最终应该看起来像这样:

【问题讨论】:

  • 到目前为止您尝试过什么,效果如何?
  • 我试过只做 df1.plot(),这不是我想要的(错误的轴标签——y 轴是时间,x 是高度)。我对matplotlib不太了解,所以这就是为什么

标签: python pandas matplotlib graph regression


【解决方案1】:
import matplotlib.pyplot as plt

plt.plot(list of things on x-axis, list of things on y-axs)
plt.show

【讨论】:

    【解决方案2】:
    import matplotlib.pyplot as plt
    
    plt.plot(times_squared_variable, 2_height_variable, '--', color='choose_a_color')
    
    # Label axis and the plot
    plt.xlabel('Name_x_axis')
    plt.ylabel('Name_y_axis')
    plt.title('Plot_name')
    
    # Show the plot
    plt.show()
    
    

    【讨论】:

      【解决方案3】:

      在您的评论中,您说您使用df1.plot() 来画线。 df.plot() 默认使用数据帧索引作为 x 值。您说 您希望 y 轴是 2 * 索引值,而 x 轴是列内的时间平方。您的需求涉及对数据框值的更改,因此我建议您使用ax.plot() 进行更好的自定义。

      这是一个使用numpy.linalg.lstsq的程序,它在内部采用Least squares来获得给定点之间的匹配线。

      import pandas as pd
      import numpy as np
      import matplotlib.pyplot as plt
      from io import StringIO
      
      TESTDATA = StringIO("""Height     Trial:1  Trial:2  Trial:3  Trial:4  Trial:5  Trial:6  Trial:7
      1.029    0.4667    0.4616    0.4569    0.4579    0.4653    0.4578    0.4484
      1.095    0.4752    0.4773    0.4721    0.4738    0.4713    0.4745    0.4663
      1.168    0.4836    0.4834    0.4873    0.4890    0.4890    0.4904    0.4902
      1.315    0.5139    0.5117    0.5161    0.5108    0.5224    0.5129    0.5187
      1.540    0.5644    0.5677    0.5804    0.5535    0.5636    0.5605    0.5609
      1.807    0.6051    0.6124    0.6014    0.6035    0.5977    0.6012    0.6209
      """)
      
      df = pd.read_csv(TESTDATA, delim_whitespace=True)
      df.set_index(['Height'], inplace=True)
      
      fig, ax = plt.subplots()
      
      for column in df:
          x = df[column]**2
          y = df.index*2
          A = np.vstack([x, np.ones(len(x))]).T
          k, b = np.linalg.lstsq(A, y)[0]
          line = ax.plot(x, y, 'o')
          ax.plot(x, k*x+b, label=f'y={k:.5f}x+{b:.5f}', color=line[0].get_color(), linestyle='dashed')
      
      plt.legend()
      
      plt.xlabel('Fall time, squared (s²)')
      plt.ylabel('Twice the height (m)')
      plt.title('Measurement of Acceleration due to Gravity on Earth')
      
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 2015-05-10
        • 2013-04-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-13
        • 1970-01-01
        • 2012-05-08
        • 1970-01-01
        相关资源
        最近更新 更多