Issue
I'm trying to plot graphs in spyder but every line in my code starts a new plot. I've tried using the example from one of the python tutorials whose code I'm including and the same happens.
import matplotlib.pyplot as plt
x = [1,2,3]
y = [5,7,4]
x2 = [1,2,3]
y2 = [10,14,12]
plt.plot(x, y, label='First Line')
plt.plot(x2, y2, label='Second Line')
plt.xlabel('Plot Number')
plt.ylabel('Important var')
plt.title('Interesting Graph\nCheck it out')
plt.legend()
plt.show()
Each line produces a new plot instead of adding to the first one. So plt.xlabel gives a new empty plot with an x label instead of adding an x label to the original plot, plt.ylabel does the same and so on.
This is probably a stupid question but I'd really appreciate any help.picture of plots
Solution
You have to create an unique axis and then add the plots to that axis.
You can do it by creating subplots. Try with this code:
import matplotlib.pyplot as plt
# Data:
x = [1,2,3]
y = [5,7,4]
x2 = [1,2,3]
y2 = [10,14,12]
# Figure creation:
fig, ax = plt.subplots()
ax.plot(x, y, label = 'First Line' )
ax.plot(x2, y2, label = 'Second Line')
ax.set_xlabel('Plot Number', fontsize = 12)
ax.set_ylabel('Important var', fontsize = 12)
ax.set_title('Interesting Graph\nCheck it out', fontsize = 12)
ax.legend()
plt.show()
If you would like to create two axis, you could do it this way:
fig, (ax1, ax2) = plt.subplots(2)
And then add the plot to its axis on an independent way.
ax1.plot(x, y, label = 'First Line' )
ax2.plot(x2, y2, label = 'Second Line')
Answered By - Miguel Gonzalez
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.