I have 3 lists (V_avg, H_avg, J_avg) containing 9 figures each (array of object with figure object of matplotlib.figure module) that I saved with PIL Image.
I would like to plot these with a subplot.
I tried like this but I received the error: TypeError: float() argument must be a string or a number, not 'Figure'.
fig, axes = plt.subplots(3, 9)
for j in range(len(axes[0])):
axes[0][j].plot(V_avg[j])
axes[1][j].plot(H_avg[j])
axes[2][j].plot(J_avg[j])
plt.show()
How can I solve it? Or should I save the figures in another way to then be able to plot with a subplots?
Thanks in advance!
Related
I wanna display in a list of lists the images inside it using matplotlib. So for example I wanna have in the first row, the images of the first list, the second row, the images of the second list and so on. I tried this, but I obtain the images in each row, maybe because it will call over and over again subplot. How can I fix it?
index_plot=0
for query in list_plot:
for qm_images in query:
plt.subplot(3,5,index_plot+1)
plt.imshow(np.array(Image.open(qm_images)))
plt.show()
index_plot += 1
Instead of creating many subplots initially create a nested list of subplots with plt.subplots(), call imshow on each axis
import matplotlib.pyplot as plt
fig, axs = plt.subplots(3, 6)
for i, query in enumerate(list_plot):
for j, qm_images in enumerate(query:
axs[i][j].imshow(np.array(Image.open(qm_images)))
plt.show()
I've been struggling to generate the frequency plot of 2 columns named "Country" and "Company" in my DataFrame and show them as 2 subplots. Here's what I've got.
Figure1 = plt.figure(1)
Subplot1 = Figure1.add_subplot(2,1,1)
and here I'm going to use the bar chart pd.value_counts(DataFrame['Country']).plot('barh')
to shows as first subplot.
The problem is, I cant just go: Subplot1.pd.value_counts(DataFrame['Country']).plot('barh') as Subplot1. has no attribute pd. ~ Could anybody shed some light in to this?
Thanks a million in advance for your tips,
R.
You don't have to create Figure and Axes objects separately, and you should probably avoid initial caps in variable names, to differentiate them from classes.
Here, you can use plt.subplots, which creates a Figure and a number of Axes and binds them together. Then, you can just pass the Axes objects to the plot method of pandas:
from matplotlib import pyplot as plt
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4))
pd.value_counts(df['Country']).plot('barh', ax=ax1)
pd.value_counts(df['Company']).plot('barh', ax=ax2)
Pandas' plot method can take in a Matplotlib axes object and direct the resulting plot into that subplot.
# If you want a two plots, one above the other.
nrows = 2
ncols = 1
# Here axes contains 2 objects representing the two subplots
fig, axes = plt.subplots(nrows, ncols, figsize=(8, 4))
# Below, "my_data_frame" is the name of your Pandas dataframe.
# Change it accordingly for the code to work.
# Plot first subplot
# This counts the number of times each country appears and plot
# that as a bar char in the first subplot represented by axes[0].
my_data_frame['Country'].value_counts().plot('barh', ax=axes[0])
# Plot second subplot
my_data_frame['Company'].value_counts().plot('barh', ax=axes[1])
I want to make a series of figures with 3x3 subplots using matplotlib. I can make the first figure fine (9 total subplots), but when I try to make a tenth subplot I get this error: ValueError: num must be 1 <= num <= 9, not 10. What I think I want to do is plot the first 9 subplots, clear the figure, and then plot the next 9 subplots. I haven't been able to get this approach to work so far though. If anyone could offer some suggestions I would really appreciate it!
Thanks!
Call plt.show() before the 10th chart, then start over with plt.subplot(3, 3, 1), followed by the code to plot the 10th chart
You have to define a new figure after plotting each subplot of the first figure.
for ex-
import matplotlib.pyplot as plt
plt.figure(1)
fig, ax = plt.subplots(3,3)
plt.figure(2)
fig, ax = plt.subplots(3,3)
plt.show()
Output:
I am plotting a bar chart on the left axis and a line chart on the right axis. How can I show the legend for both in the same legend box?
With the code below, I get two separate legend boxes; also, I need to specify the location of the second legend manually, with lots of trial-and-error, otherwise it overlaps the first one.
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
df=pd.DataFrame()
df["bar"]=[40,35,50,45]
df["line"]=[.5,.3,.2,.6]
fig,ax=plt.subplots(2)
l1 = ax[0].bar(df.index, df["bar"], label='my bar chart (left axis)', color='royalblue', width = 0.55)
ax0b=ax[0].twinx()
l2 = ax0b.plot(df.index, df['line'], label='my line (right axis)',color='tomato',marker='.', ls='dashed')
ax[0].legend(loc='upper left', fancybox=True, title='My title')
ax0b.legend(bbox_to_anchor=(0.155,0.8), loc=1)
plt.show()
If I had two lines on two different axes, instead of a bar chart and a line chart, I'd do:
myl=l1+l2
labs=[l.get_label() for l in myl]
ax[0].legend(myl, labs, loc='upper left')
But this doesn't work in my case. I get:
myl=l1+l2
TypeError: can only concatenate tuple (not "list") to tuple
which I imagine must be because bar() and plot() return two different objects which cannot be concatenated.
The good thing about python errors is that they most often can be taken literally and directly tell you the problem.
"TypeError" tells you that you have a problem of types. You may print the types:
print(type(l1)) # <class 'matplotlib.container.BarContainer'>
print(type(l2)) # <type 'list'>
Now, "can only concatenate tuple (not "list") to tuple" tells you that you cannot add a barcontainer to a list.
Easy solution: Add two lists:
myl=[l1]+l2
I am using the pandas plotting function for histogram subplots.
df.plot.hist(subplots = True)
I would like to add a vertical line to each of the plots. I know you can do this in matplotlib plot using
plt.axvlines
But how do I access the individual subplots generated by pandas?
I looked at :Is there a way to pass different vertical lines to each subplot when using pandas histogram with "by=somevar"?
But can someone please give me an actual example of how to do this?
Thank you!
DataFrame.hist() returns a list of Axes object. You just have to iterate over each axis and add you vertical line
df = pd.DataFrame(np.random.random((100,5)))
axs = df.plot.hist(subplots = True)
for ax in axs:
ax.axvline(0.5)
I was facing the same issue you mentioned:
ax = daily_returns.hist(bins=20) # changing no. of bins to 20
print(ax)
And by printing the result I got:
[[<matplotlib.axes._subplots.AxesSubplot object at 0x0000021F1BEBEF28>
<matplotlib.axes._subplots.AxesSubplot object at 0x0000021F1C0F8208>]]
So in my case I woulnd need to do something like ax[0][0] and ax[0][1] to get to the axes