I want to plot data, in two different subplots. After plotting, I want to go back to the first subplot and plot an additional dataset in it. However, when I do so I get this warning:
MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance. warnings.warn(message, mplDeprecation, stacklevel=1)
I can reproduce that with a simple piece of code:
import matplotlib.pyplot as plt import numpy as np # Generate random data data = np.random.rand(100) # Plot in different subplots plt.figure() plt.subplot(1, 2, 1) plt.plot(data) plt.subplot(1, 2, 2) plt.plot(data) plt.subplot(1, 2, 1) # Warning occurs here plt.plot(data + 1)
Any ideas on how to avoid this warning? I use matplotlib 2.1.0. Looks like the same problem as here
To create a secondary y-axis, use the twinx() function. To set the limit of the secondary y-axis, we use plt. axis() function. Here we set xmin and xmax values to None as we don't want to change the limit of the x-axis.
set_aspect() to Make a Square Plot With Equal Axes Axes. set_aspect() function. If we use "equal" as an aspect ratio in the function, we get a plot with the same scaling from data points to plot units for X-axis and Y-axis. It sets both X-axis and Y-axis to have the same range.
The xticks() and yticks() function takes a list object as argument. The elements in the list denote the positions on corresponding action where ticks will be displayed. This method will mark the data points at the given positions with ticks.
This is a good example that shows the benefit of using matplotlib
's object oriented API.
import numpy as np import matplotlib.pyplot as plt # Generate random data data = np.random.rand(100) # Plot in different subplots fig, (ax1, ax2) = plt.subplots(1, 2) ax1.plot(data) ax2.plot(data) ax1.plot(data+1) plt.show()
Note: it is more pythonic to have variable names start with a lower case letter e.g. data = ...
rather than Data = ...
see PEP8
Using plt.subplot(1,2,1)
creates a new axis in the current figure. The deprecation warning is telling that in a future release, when you call it a second time, it will not grab the previously created axis, instead it will overwrite it.
You can save a reference to the first instance of the axis by assigning it to a variable.
plt.figure() # keep a reference to the first axis ax1 = plt.subplot(1,2,1) ax1.plot(Data) # and a reference to the second axis ax2 = plt.subplot(1,2,2) ax2.plot(Data) # reuse the first axis ax1.plot(Data+1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With