python - 基于行的图表绘制(Seaborn 或 Matplotlib)

标签 python python-2.7 pandas matplotlib seaborn

鉴于我的数据是 pandas 数据框,如下所示:

            Ref   +1    +2    +3    +4    +5    +6    +7  
 2013-05-28  1  -0.44  0.03  0.06 -0.31  0.13  0.56  0.81 
 2013-07-05  2   0.84  1.03  0.96  0.90  1.09  0.59  1.15 
 2013-08-21  3   0.09  0.25  0.06  0.09 -0.09 -0.16  0.56 
 2014-10-15  4   0.35  1.16  1.91  3.44  2.75  1.97  2.16 
 2015-02-09  5   0.09 -0.10 -0.38 -0.69 -0.25 -0.85 -0.47 

如何绘制 5 条线(每个引用 1 条)的图表,其中 X 轴是列(+1、+2...),并从 0 开始?如果是在seaborn就更好了。但 matplotlib 解决方案也很受欢迎。

最佳答案

在 pandas 中绘制数据框通常都是关于 reshape 表格,以便您想要的各个行位于单独的列中,并且 x 值位于索引中。其中一些 reshape 操作有点难看,但您可以这样做:

df = pd.read_clipboard()
plot_table = pd.melt(df.reset_index(), id_vars=['index', 'Ref'])
plot_table = plot_table.pivot(index='variable', columns='Ref', values='value')
# Add extra row to have all lines start from 0:
plot_table.loc['+0', :] = 0
plot_table = plot_table.sort_index()
plot_table
Ref          1     2     3     4     5
variable                              
+0        0.00  0.00  0.00  0.00  0.00
+1       -0.44  0.84  0.09  0.35  0.09
+2        0.03  1.03  0.25  1.16 -0.10
+3        0.06  0.96  0.06  1.91 -0.38
+4       -0.31  0.90  0.09  3.44 -0.69
+5        0.13  1.09 -0.09  2.75 -0.25
+6        0.56  0.59 -0.16  1.97 -0.85
+7        0.81  1.15  0.56  2.16 -0.47

现在您已经有了一个形状正确的表格,绘图就非常自动了:

plot_table.plot()

关于python - 基于行的图表绘制(Seaborn 或 Matplotlib),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29933420/

相关文章:

Python 程序未按预期运行

python - 无法将 Django 模型导入 celery 任务

python - 如何处理我的 UnicodeDecodeError?

Pandas 将多列与一列进行比较

python - pip 安装 Pandas : installing dependencies error

python - 为什么从 QListWidgetItem 和 QObject 派生时会崩溃

python - Django 应用程序的 Heroku 部署失败

multithreading - 线程 : PyQt crashes with "unknown request in queue while dequeuing"

python - 使用 Swig 和 distutils 为 Python 3 构建扩展

python - 如何取消 Pandas 数据透视表的透视?