I'm new to python and I'm trying to plot a line graph of two data series using matplotlib.
Here's the sample code:
import matplotlib.pyplot as plt
# choronologically sorted dates with frequencies
date_1, freq_1 = [...], [...]
date_2, freq_2 = [...], [...]
fig, ax = plt.subplots()
ax.plot(date_1, freq_1, c='blue')
ax.plot(date_2, freq_2, c='red')
plt.legend()
plt.title("Date and frequency")
plt.ylabel("Frequency")
ax.get_xaxis().set_visible(False)
fig.autofmt_xdate()
plt.show()
Commenting out the first or second plot produces no issues, as shown: , .
But when trying to plot both at the same time, I get weird straight lines in my plot: .
Plotting the second plot first gives .
What is happening here and what's the most beginner friendly way to correct it?
CodePudding user response:
Most likely you have an outlier or a datapoint that is out of place. I would suggest plotting the data like this first just to make sure if it is indeed an out-of-context point:
ax.plot(date_1, freq_1, '.', c='blue')
ax.plot(date_2, freq_2, '.',c='red')
Then maybe try to sort the point according to the x. Or remove the outlier.
From the graph, most likely you have a point that is (0, 0) somewhere in the middle of your data.
CodePudding user response:
Without data this is hard to answer - it looks as if you got either non-sorted data with a regressing to 0 in your plots data:
import matplotlib.pyplot as plt
# choronologically sorted dates with frequencies
date_1, freq_1 = [1,2,3], [4,5,6]
date_2, freq_2 = [1,2,1,3,], [6,7,0,8]
fig, ax = plt.subplots()
ax.plot(date_1, freq_1, c='blue')
ax.plot(date_2, freq_2, c='red')
plt.legend()
plt.title("Date and frequency")
plt.ylabel("Frequency")
ax.get_xaxis().set_visible(False)
fig.autofmt_xdate()
plt.show()
Having a NaN
in your data would give you a break in your graph: