[英]Pyplot - How do I plot multiple lines on the same graph when list lengths for one axis are not consistent?
I am trying to plot multiple lines on the same graph, one of the axis lists consists of dates and the other is a list of the numbers corresponding to each of the dates.我正在尝试 plot 在同一图表上的多条线,其中一个轴列表由日期组成,另一个是与每个日期对应的数字列表。 However, when I go to plot the second line, the dates list is different in contents and length from first line plotted.
但是,当我从 go 到 plot 第二行时,日期列表的内容和长度与绘制的第一行不同。 So to try and fix this I put all of the dates used into 1 array and used this for the y-axis.
因此,为了尝试解决这个问题,我将所有使用的日期放入 1 个数组中,并将其用于 y 轴。 This then left me with the issue of the x-axis never being the same length of as the y-axis causing an error.
这给我留下了一个问题,即 x 轴的长度永远不会与 y 轴的长度相同,从而导致错误。 In an attempt to fix this I tried the following:
为了解决这个问题,我尝试了以下方法:
while len(y) != len(dates):
y.insert(0, 0)
plt.plot(dates, y) # plots the line for x (dates) and y
This fixes the error however the graph now plots 0's when it should be plotting 1's.这修复了错误,但是图表现在应该在绘制 1 时绘制 0。
The graph should be plotting on 0.1 instead of 0.0该图应绘制在 0.1 而不是 0.0
So what I'm asking is how would I fill the y-axis list with the zero's in the correct position, relevant to the dates, rather than putting all of the zero's at the beginning of the list?所以我要问的是如何在与日期相关的正确 position 中用零填充 y 轴列表,而不是将所有零放在列表的开头?
Plot the two sets of data in separate calls. Plot 这两组数据分别调用。 Here's an example:
这是一个例子:
from datetime import datetime
import matplotlib.pyplot as plt
derby_dates = [datetime(2020, 3, 1),
datetime(2020, 3, 2),
datetime(2020, 3, 3),
datetime(2020, 3, 6)]
derby_cases = [1, 10, 7, 12]
nottingham_dates = [datetime(2020, 3, 1), datetime(2020, 3, 2)]
nottingham_cases = [2, 5]
plt.plot(derby_dates, derby_cases)
plt.plot(nottingham_dates, nottingham_cases)
plt.xticks(rotation=30)
plt.tight_layout()
plt.show()
That plots like this:像这样的情节:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.