【问题标题】:How to plot lines from a dataframe with column headers as the x-axis如何从以列标题为 x 轴的数据框中绘制线条
【发布时间】:2021-12-02 16:09:36
【问题描述】:

我想我需要对数据进行某种排序/以不同的方式显示它以绘制图表,但我不确定如何。我尝试过转置数据集,但这似乎也不起作用。

这是我切片后的数据,我需要将 W 值绘制为 x 轴,将 R 值绘制为 y1、y2、y3、y4 和 y5

import pandas as pd

data = {'observations': [15, 28, 10, 6, 25],
        'biomass': [94.67, 56.56, 81.33, 26.00, 65.78],
        380: [0.013918, 0.012229, 0.013622, 0.015602, 0.011784],
        390: [0.015578, 0.012762, 0.014548, 0.017856, 0.013304],
        400: [0.016338, 0.014434, 0.014872, 0.019132, 0.014054]}
data1 = pd.DataFrame(data, index=[14, 17, 9, 5, 24])

data1.plot()

【问题讨论】:

    标签: python pandas matplotlib plot


    【解决方案1】:
    1. 对数据帧进行采样后,将索引值更改为所需的y1 to yn+1 格式
    2. .iloc选择所需的列,它选择索引2中的所有行和列,然后用.T转置数据帧
      • 索引将是 x 轴,每列将是一个线图
    3. pandas.DataFrame.plot 绘制数据帧,以matplotlib 作为后端绘制。
    • python 3.8.11pandas 1.3.3matplotlib 3.4.3中测试
    import pandas as pd
    
    # given the sample in the OP, relabel the index values
    data1.index = [f'y{i}' for i in range(1, len(data1)+1)]
    
    # display(data1)
        observations  biomass       380       390       400
    y1            15    94.67  0.013918  0.015578  0.016338
    y2            28    56.56  0.012229  0.012762  0.014434
    y3            10    81.33  0.013622  0.014548  0.014872
    y4             6    26.00  0.015602  0.017856  0.019132
    y5            25    65.78  0.011784  0.013304  0.014054
    
    # select data and transpose
    data1 = data1.iloc[:, 2:].T
    
    # display(data1) - Note the difference after selecting columns and transposing
               y1        y2        y3        y4        y5
    380  0.013918  0.012229  0.013622  0.015602  0.011784
    390  0.015578  0.012762  0.014548  0.017856  0.013304
    400  0.016338  0.014434  0.014872  0.019132  0.014054
    
    # plot
    ax = data1.plot(xlabel='Wavelength', ylabel='Reflectance', figsize=(10, 5), marker='.', xticks=data1.index.tolist())
    ax.legend(title='Sample', bbox_to_anchor=(1, 1.02), loc='upper left')
    

    【讨论】:

      【解决方案2】:

      对于每个图形,您需要两个数组或列表 x 和 y。

      由于每个图形的 x 值都是相同的,因此您可以重复使用它们。您可以像这样从 DataFrame 的键(假设它们是整数)中获取它们:

      x = [key for key in df.keys() if type(key) == int]
      

      接下来,您需要每个图表的 y 值。您可以使用 df.iterrows() 迭代 DataFrame 的行:

         fig, ax = plt.subplots()    # create figure and axes
         for index, row in data1[x].iterrows(): 
              ax.plot(x, row)
         plt.show()
      

      data1[x] 返回 x 中的列

      iterrows()返回索引和行的元组。 Row 是 pandas.Series 类型

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-02
        • 1970-01-01
        相关资源
        最近更新 更多