首页 > 解决方案 > 使用循环创建 Matplotlib 绘图

问题描述

我有工作代码可以生成我正在寻找的确切图表。但是,它是硬编码的(尤其是图例),我认为有一种方法可以在循环中制作相同的图表。

这是我的代码:

import pandas as pd
import matplotlib.pyplot as plt
raw_data = {'Time':       [1,    2,    3,    4,    5,    6 ,  7,    8,   9,      10],
        'Drug 1':     [23.4, 32.5, 45.6, 46.1, 47.8, 50.1, 51.2, 53.2, 54.5, 55.0],
        'Drug 2':    [10.4,  12.5, 13.7, 13.8, 14.0, 15.6, 17.7, 23.2, 20.4, 19.5], 
        'Drug 3':    [0.4,   1.5,  2.6,  3.7,  4.8,  5.9,  6.2,  8.7,  12.8, 13],
        'Drug 4':    [45,    47,   48,   50,   51,     52,   55,  60,   61,   67],
        'Drug 5':    [17,    21,    20, 20,    20,     24,    26,  28, 29,   30]}


df = pd.DataFrame(raw_data)

plt.errorbar(x = df['Time'], y = df['Drug 1'], yerr=None, linestyle = "--")
plt.errorbar(x = df['Time'], y = df['Drug 2'], yerr=None, linestyle = "--")
plt.errorbar(x = df['Time'], y = df['Drug 3'], yerr=None, linestyle = "--")
plt.errorbar(x = df['Time'], y = df['Drug 4'], yerr=None, linestyle = "--")
plt.errorbar(x = df['Time'], y = df['Drug 5'], yerr=None, linestyle = "--")

plt.legend(['Drug 1', 'Drug 2', 'Drug 3', 'Drug 4', 'Drug 5'], loc = 2)

plt.ylabel('Tumor Size')
plt.xlabel('Time in Years')

plt.title('Effect on Treatment')
plt.grid()

plt.show()

我知道有五行全部调用plt.errorbar不是最佳的,像我一样对图例进行硬编码,也不是最佳的。

我尝试使用以下方法从头开始:

for x in df:
    print(x)

...但这包括 $Time$ 列,因此我不确定如何始终将时间设为 x 轴,然后遍历其余列以获取 y。

标签: pythonpandasmatplotlib

解决方案


你可以这样做:

for col in df.columns[1:]:
    plt.errorbar(x=df['Time'], y=df[col], linestyle='--',label=col)

plt.legend(loc=2)

或者,如果您没有要传递的错误errorbar

df.plot(x='Time', linestyle='--')

输出:

在此处输入图像描述


推荐阅读