【问题标题】:Matplotlib - Plot uneven steps from DataFrameMatplotlib - 从 DataFrame 绘制不均匀的步骤
【发布时间】:2020-11-23 04:41:05
【问题描述】:

我有这个DataFrame,x 轴数据按列组织。但是,对于不存在的,列被省略了,所以步骤是不均匀的。例如:

   0.1  0.2  0.5 ...
0    1    4    7 ...
1    2    5    8 ... 
2    3    6    9 ...

我想用 x 轴 np.arange(0, max(df.columns), step=0.1) 绘制每个图,并结合这些图。有没有什么简单的方法可以通过matplotlib.pyplot 实现这一目标?

plt.plot(np.arange(0, max(df.columns), step=0.1), new_data)

任何帮助将不胜感激。

【问题讨论】:

  • 你需要什么类型的情节?
  • @steven 折线图
  • 您能说得更具体些吗?每一步都有一列数据。一定有一些分组吧?喜欢每一行都有一行吗?
  • @steven 是的,每行一行
  • 由于您希望列标题为 x 轴,行为单独的行,也许您的意思是像 plt.plot(df.T) 一样绘制数据,即“旋转”90 度?

标签: python python-3.x pandas matplotlib


【解决方案1】:

如果我理解正确,您的最终数据框应该如下所示:

   0.0  0.1  0.2  0.3  0.4  0.5
0  0.0    1    4  0.0  0.0    7
1  0.0    2    5  0.0  0.0    8
2  0.0    3    6  0.0  0.0    9

可以像这样生成(然后也可以绘制):

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

df = pd.DataFrame({0.1:[1,2,3],0.2:[4,5,6],0.5:[7,8,9]})

## make sure to actually include the maximum value (add one step)
#  or alternatively rather use np.linspace() with appropriate number of points
xs = np.arange(0, max(df.columns) +0.1, step=0.1)

df = df.reindex(columns=xs, fill_value=0.0)

plt.plot(df.T)
plt.show()

产生:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多