I have the following code:
pl.bar (x1,x2)
pl.show()
pl.plot(x1,x3)
pl.show
It generated two separate chart one bar chart and one plot. I want to have bar and plot in one single graph. Could you please let me know how I can make it?
Thanks,
Amir
Assuming pl is matplotlib.pylab:
pl.bar(x1,x2)
pl.plot(x1,x3,color='r')
pl.show()
Note the change of color for contrast.
Take out the first call to pl.show(). This way you add both items to pl before showing it.
Related
[shot from Jupyter][1]
I am trying to display two plots output from function to be together in the same output.
Can anyone help?
thanks
[1]: https://i.stack.imgur.com/ABXMj.png
You can either use plt.subplots() or else you can do the one as shown in the picture too by coding all the plots together and then giving plt.show() at last.
Below each plot code use plt.plot():
fig, axes = plt.subplots(1,2)
plt.plot(ax=axes[0])
plt.plot(ax=axes[1])
I have successfully created a figure of four sub-plots and two of subplots having double y-axis features as shown below. Each subplot has many different plots. I wanted to add a legend. But, I could not do it with code. The figure is given below:
My code is given below:
fig, axs = plt.subplots(2,2,figsize=(17,10))
fig.legend(loc="center right", fontsize=13,fancybox=True, framealpha=1, shadow=True, borderpad=1)
plt.rc('font',family='Times New Roman')
.
.
for i,j in zip(IV_start_index,IV_start_index[1:]): # This is simple code to access present and next element in a list
axs[0][0].plot(module_allData_df['Time'].iloc[mpp_index],pmpp_theo,'bs',label="Theoretical")
axs[0][0].plot(module_allData_df['Time'].iloc[mpp_index],pmpp_act,'rd',label="Actual")
.
.
plt.suptitle('A NIST Module %s power loss analysis'%(module_allData_df['Time'].loc[i].strftime('%Y-%m-%d')),fontsize=18) #
plt.savefig('All_day_power_loss')
The output is:
No handles with labels found to put in legend.
Could you help me to correct my code?
Corrections:
I did change the code as given below.
for i,j in zip(IV_start_index,IV_start_index[1:]): # This is simple code to access present and next element in a list
axs[0][0].plot(module_allData_df['Time'].iloc[mpp_index],pmpp_theo,'bs',label="Theoretical")
axs[0][0].plot(module_allData_df['Time'].iloc[mpp_index],pmpp_act,'rd',label="Actual")
axs[0][0].legend()
It has created many legends.The output figure is given below:
If you don't provide the legend entries within the legend() function, it should be placed after the label-entries in the plot commands. Otherwise legend cannot know what to list.
If you want to have a legend within each subplot, you should call axs[i][j].legend() within a loop (or call axs[0][0].legend(), axs[0][1].legend(), ... manually for each subplot of course). The point is: fig.legend() is a legend on figure level, i.e. one legend for all subplots together. This should be called once outside of the loop.
After a series of trails, I did the following to my code:
for i,j in zip(IV_start_index,IV_start_index[1:]): # This is simple code to access present and next element in a list
axs[0][0].plot(module_allData_df['Time'].iloc[mpp_index],pmpp_theo,'bs')
axs[0][0].plot(module_allData_df['Time'].iloc[mpp_index],pmpp_act,'rd')
axs[0][0].legend(['Theoretical','Actual'])
.
.
My output is:
Disclaimer: I am very inexperienced using matplotlib and python in general.
Here is the figure I'm trying to make:
Using GridSpec works well for laying out the plots, but when I try to include a colorbar on the right of each row, it changes the size of the corresponding subplot. This seems to be a well known and unavoidable problem with GridSpec. So at the advice of this question: Matplotlib 2 Subplots, 1 Colorbar
I've decided to remake the whole plot using ImageGrid. Unfortunately the documentation only lists the options cbar_mode=[None|single|each] whereas I want 1 colobar per row. Is there a way to do this inside a single ImageGrid? or will I have to make 2 grids and deal with the nightmare of alignment.
What about the 5th plot at the bottom? Is there a way to include that in the image grid somehow?
The only way I can see this working is to somehow nest two ImageGrids into a GridSpec in a 1x3 column. this seems overly complicated and difficult so I don't want to build that script until I know its the right way to go.
Thanks for any help/advice!
Ok I figured it out. It seems ImageGrid uses subplot somehow inside it. So I was able to generate the following plot using something like
TopGrid = ImageGrid( fig, 311,
nrows_ncols=(1,2),
axes_pad=0,
share_all=True,
cbar_location="right",
cbar_mode="single",
cbar_size="3%",
cbar_pad=0.0,
cbar_set_cax=True
)
<Plotting commands for the top row of plots and colorbar>
BotGrid = ImageGrid( fig, 312,
nrows_ncols=(1,2),
axes_pad=0,
share_all=True,
cbar_location="right",
cbar_mode="single",
cbar_size="3%",
cbar_pad=0.0,
)
<Plotting commands for bottom row . . .>
StemPlot = plt.subplot(313)
<plotting commands for bottom stem plot>
EDIT: the whitespace in the color plots is intentional, not some artifact from adding the colorbars
I have a string "Line2D" appended in the beginning of my matplotlib legend. How to get rid of it? A simple python script that reproduces this problem is as follows:
import numpy as np
import matplotlib.pylab as plt
x=np.linspace(0,1,20)
y=np.sin(2*x)
z=np.cos(2*x)
p1, = plt.plot(x,y, label='sin(x)')
p2, = plt.plot(x,z, label='cos(x)')
plt.legend([p1, p2])
plt.show()
I get a figure in which I want to get rid of the extra string "Line2D" in the legend. I do not have enough reputation to post images. I was using anaconda python if that matters.
Thanks for your help!
If you pass just one list to legend, it has to be the labels you want to show, not the objects whose labels you want to show. It is converting those line objects to strings, which gives Line2D(...).
Since you gave the lines labels when you created them, you don't need to pass anything to legend. Just plt.legend() will automatically use the labels you provided.
You can use plt.legend(handles=[p1, p2]).
I have started my IPython Notebook with
ipython notebook --pylab inline
This is my code in one cell
df['korisnika'].plot()
df['osiguranika'].plot()
This is working fine, it will draw two lines, but on the same chart.
I would like to draw each line on a separate chart.
And it would be great if the charts would be next to each other, not one after the other.
I know that I can put the second line in the next cell, and then I would get two charts. But I would like the charts close to each other, because they represent the same logical unit.
You can also call the show() function after each plot.
e.g
plt.plot(a)
plt.show()
plt.plot(b)
plt.show()
Make the multiple axes first and pass them to the Pandas plot function, like:
fig, axs = plt.subplots(1,2)
df['korisnika'].plot(ax=axs[0])
df['osiguranika'].plot(ax=axs[1])
It still gives you 1 figure, but with two different plots next to each other.
Something like this:
import matplotlib.pyplot as plt
... code for plot 1 ...
plt.show()
... code for plot 2...
plt.show()
Note that this will also work if you are using the seaborn package for plotting:
import matplotlib.pyplot as plt
import seaborn as sns
sns.barplot(... code for plot 1 ...) # plot 1
plt.show()
sns.barplot(... code for plot 2 ...) # plot 2
plt.show()
Another way, for variety. Although this is somewhat less flexible than the others. Unfortunately, the graphs appear one above the other, rather than side-by-side, which you did request in your original question. But it is very concise.
df.plot(subplots=True)
If the dataframe has more than the two series, and you only want to plot those two, you'll need to replace df with df[['korisnika','osiguranika']].
I don't know if this is new functionality, but this will plot on separate figures:
df.plot(y='korisnika')
df.plot(y='osiguranika')
while this will plot on the same figure: (just like the code in the op)
df.plot(y=['korisnika','osiguranika'])
I found this question because I was using the former method and wanted them to plot on the same figure, so your question was actually my answer.