Matplotlib: plotting on old plot - python

After review this question (How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?) I thought I had figured this out, but I think I'm running into an issue with my for loops. Here is a pared down version of what I'm doing.
import matplotlib.pyplot as plt
import numpy as np
for m in range(2):
x=np.arange(5)
y=np.exp(m*x)
plt.figure(1)
plt.plot(x, y)
plt.show()
...
z=np.sin(x+(m*math.pi))
plt.figure(2)
plt.plot(x,z)
...
plt.figure(2)
plt.show()
My hope was that this would display three plots: a plot for e^(0) vs x the first time through, a plot of e^x vs x the second time through, and then one plot with both sin(x) and sin(x+pi) vs x.
But instead I get the first two plots and a plot with just sin(x) and plot with just sin(x+pi).
How do I get all the data I want on to figure 2? It seems to be some sort of issue with the set figure resetting when I return to the beginning of the loop.

This minimal change will probably do what you want (although it is not the best code).
Replace plt.figure(1) with plt.figure(). Remove any plt.show() from inside the loop.
The loop will end and then all 3 figures will be shown. The e^x curves will be in figures #1 and #3.

Related

Matplotlib | Python | Plotting figure A and then plotting another figure B on top of figure A

The fragment of code below plots a figure based on two arrays of floats
plt.scatter(t, h)
plt.xlabel("time")
plt.ylabel("height")
plt.show()
Then, after defining a function y(t), I need to add the following on top of the last plot:
plt.plot(t, y(t), 'r')
plt.show()
However, the code above generates two separate plots. I've noticed that if I comment out the first plt.show(), I'll get the second figure I am looking for. But is there a way to show them both?
I was expecting one plot and then another plot on top of the second one; however the second plot is shown as a new one
plt.show() draws your figure on screen.
So, you need to remove the first plt.show() from your code.
If you remove the first plt.show() you should see the joint plot. The first plt.scatter just produces points on the joints of the line.
import numpy as np
import matplotlib.pyplot as plt
t = np.random.random(10)
h = np.random.random(10)
plt.scatter(t, h)
plt.plot(t, h, 'r')
plt.show()
The scatter plot is just the blue dots

How do I use mathlibplot.hist with x and y values using bins=40 in Python 3?

I have a large list of data points of x and y values that I need to put into a histogram with 40 bins but mathlibplot.hist is only letting me enter 1 variable with bins. I've tried hist2d as well but it's not very clean. Any help would be appreciated!
As you have data points x and y, you can simply use hist method to plot histogram.
The following code will help you to create a histogram.
plt.hist([x,y],bins=40, histtype='step',fill=True)
plt.show()
The histogram will look like the following:
If you want to change the style or give it title and labels, you can do it. Here is another histogram with unfilled bars.
If you still face any problem, let me know then.
Maybe you can make use of matplotlib library to solve your purpose:
It will be like imposing 2 histograms on top of each other.
In the below code, I am trying to plot a histograms of y_train and predicted(X_train) in the same space.
You can modify the variables as per your requirement.
import matplotlib.pyplot as plt
plt.hist(y_train, stacked=True,bins=40, label='Actual', alpha=0.5)
plt.hist(regressor.predict(X_train),bins=40, stacked=True, label='Predicted', alpha=0.5)
plt.legend(loc='best')
plt.show()
Hope this helps!

Overplot trends in matplotlib: every loop gives additional trend

With the code below I get three different plots, and I would like to know how to combine them so that I have three lines on one plot. I thought there is something simple as overplot instead of plot, but somehow I could't find it.
Somehow I also need to adjust the x to the "longest" dataset.
import matplotlib.pyplot as plt
big_array = [[4,5,4,5],[6,4,1],[1,2,3,4]]
for i in big_array:
x = range(len(i))
y = i
plt.plot(x, y)
plt.show()
When you call plt.show() this displays all the current figures that have been drawn and blocks the rest of the code until the figure window has been closed.
As you are in a loop of 3 iterations you code will display and block the figure at each call to show. Then when you close the window your loop will continue, creating another figure when you call plt.plot() and then displays it again when you call show.
To fix you should only call plt.show() at the end of your script:
big_array = [[4,5,4,5],[6,4,1],[1,2,3,4]]
for i in big_array:
x = range(len(i))
y = i
plt.plot(x, y)
plt.show()
Which will produce the following figure:

Simple way to animate matplotlib plot without using collections

Is there a simple way to animate a scatterplot in matplotlib, in a similar way to which the plot is created?
I know currently I can do this to create the plot:
scatter = ax.scatter([x values], [y values], [z values])
However, every example I find online uses numpy functions to generate its data rather than something external like three lists, leaving me with much difficulty understanding how the data is modified in the method which updates the animation.
Is it possible to give matplotlib an entirely new set of data to plot for each frame? (every point of data will change anyway)
Note: in case there are special considerations for this situation, this is a 3D plot.
The easiest way to animate is to plot in interactive mode, as a minimal(ish) examples with lists,
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
plt.show()
for i in range(1000):
x =[1,2,3,4,5,6,7,8,9,10]
y =[5,6+i%10,2,3,13,4,1,2,4-i%10,8]
z =[2+(i%10)*2.,3,3,3,5,7,9+i%10,11,9+i%10,10]
ax.scatter(x, y, z, marker='o')
ax.set_xlim([0.,10.])
ax.set_ylim([0.,20.])
ax.set_zlim([0.,20.])
plt.pause(0.01)
plt.cla()
A reason to plot using numpy arrays instead of lists is the data is stored as a contiguous block and this speeds up plots (it's easy to convert to an array with xn = np.array(x)). The main reason most examples will use various numpy functions is that it is just easier to provide a self contained demonstration with animation in matplotlib requiring a function which adjusts the collection object. For a great example of a minimum scatter plot animation, see the second example of this.

matplotlib.pyplot issue with subplot, np.ones and np.arange?

I am plotting several data types which share the x axis so I am using the matplotlib.pylot subplots command
The shared x axis is time (in years AD). The last subplot I have is the number of independent observations as a function of the time. I have the following code
import numpy as np
import matplotlib.pyplot as plt
#
# There's a bunch of data analysis here
#
f, ax = plt.subplots(4, sharex=True)
# Here I plot the first 3 subplots with no issue
x = np.arange(900, 2000, 1)#make x array in steps of 1
ax[3].plot(x[0:28], np.ones(len(x[0:28])),'k')#one observation from 900-927 AD
ax[3].plot(x[29:62], 2*np.ones(len(x[29:62])),'k')#two observations from 928-961 AD
Now when I run this code, the subplot I get only shows the second ax[3] plot and not the first. How can I fix this?? Thanks
Ok, I think I found an answer. The first plot was plotting but I couldn't see it with the axes so I changed the y limits
ax[3].axes.set_ylim([0 7])
That seemed to work, although is there a way to connect these horizontal lines, perhaps with dashed lines?

Categories

Resources