python - 使用循环创建 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。
解决方案
推荐阅读
- javascript - 如何为文本字段实现正则表达式以在 Extjs 中一次允许一个逗号一个空格
- python - Pandas CSV 导入中二进制变量的最佳数据类型以减少内存使用
- c - 并发线程和数据竞争
- java - Draw on Android's surfaceView
- testng - 如何在循环中多次运行具有许多测试方法的 testng 类文件
- c# - c# 后面的代码中绑定了不正确的数据
- logstash - Logstash 对 Crate DB 的支持
- tsql - How to correct this if exists query?
- yarnpkg - 运行`react-scripts`时如何查找依赖项
- solr - Solr查询由父级选择的拓扑