Multiple pie charts using matplotlib - python

I'm trying to display two charts at the same time using matplotlib.
But I have to close one graph then only I can see the other graph.
Is there anyway to display both the graphs or more number of graphs at the same time.
Here is my code
num_pass=np.size(data[0::,1].astype(np.float))
num_survive=np.sum(data[0::,1].astype(np.float))
prop=num_survive/num_pass
num_dead=num_pass-num_survive
#print num_dead
labels='Dead','Survived'
sizes=[num_dead,num_survive]
colors=['darkorange','green']
mp.axis('equal')
mp.title('Titanic Survival Chart')
mp.pie(sizes, explode=(0.02,0), labels=labels,colors=colors,autopct='%1.1f%%', shadow=True, startangle=90)
mp.show()
women_only_stats = data[0::,4] == "female"
men_only_stats = data[0::,4] != "female"
# Using the index from above we select the females and males separately
women_onboard = data[women_only_stats,1].astype(np.float)
men_onboard = data[men_only_stats,1].astype(np.float)
labels='Men','Women'
sizes=[np.sum(women_onboard),np.sum(men_onboard)]
colors=['purple','red']
mp.axis('equal')
mp.title('People on board')
mp.pie(sizes, explode=(0.01,0), labels=labels,colors=colors,autopct='%1.1f%%', shadow=True, startangle=90)
mp.show()
How can I show both the graphs at the same time?

There are several ways to do this, and the simplest is to use multiple figure numbers. Simply tell matplotlib that you are working on separate figures, and then show them simultaneously:
import matplotlib.pyplot as plt
plt.figure(0)
# Create first chart here.
plt.figure(1)
# Create second chart here.
plt.show() #show all figures

In addition to Banana's answer, you could also plot them in different subplots within the same figure:
from matplotlib import pyplot as plt
import numpy as np
data1 = np.array([0.9, 0.1])
data2 = np.array([0.6, 0.4])
# create a figure with two subplots
fig, (ax1, ax2) = plt.subplots(1, 2)
# plot each pie chart in a separate subplot
ax1.pie(data1)
ax2.pie(data2)
plt.show()

Alternatively, you can put multiple pies on the same figure using subplots/multiple axes:
mp.subplot(211)
mp.pie(..)
mp.subplot(212)
mp.pie(...)
mp.show()

Yes. This answer of User:Banana worked for me.
I had 4 graphs and all 4 popped up as individual pie charts when I ran the plt.show() so I believe you can use as many figure numbers as you want.
plt.figure(0) # Create first chart here and specify all parameters below.
plt.figure(1) # Create second chart here and specify all parameters below.
plt.figure(3) # Create third chart here and specify all parameters below.
plt.figure(4) # Create fourth chart here and specify all parameters below.
plt.show() # show all figures.

Related

How to add two data sets on one bar graph using matplotlib

How do you put two data sets on the same bar graph? I tried this code. This should be simple enough to help anyone with the same problem?
x = groups1_table.plot.bar(color='blue')
x = groups2_table.plot.bar(color='red')
plt.show()
Any suggestions?
Use ax in matplotlib.
Since you have not posted MRE, I am assuming the data points.
You can proceed with something like this:
import matplotlib.pyplot as plt
x1=[1,2,3,4,5]
y1=[6,7,8,9,15]
x2=[16,17,18,16,19]
y2=[20,22,23,26,21]
fig, ax=plt.subplots()
ax=plt.bar(x1,y1,label='x_list')
ax=plt.bar(x2,y2,label='y_list')
plt.legend(loc='upper left')
plt.show()
Again you have to change the code to meet your preferences. Just know that you can place as many graphs as you want on a same plot. Just use the same axes object ax to plot them.
OUTPUT:

plot graph in a specific figure in python

Actually, I am not clear that
fig_1 = plt.figure()
plt.subplot(2,2,1)
...
Is the ploting like plt.subplot(2,2,1) and other plt. plot on the fig_1 or system will automatically create a new empty figure?
Then how to plot something in a specific figure, for example:
fig_1 = plt.figure()
fig_2 = plt.figure()
plt.subplot(2,2,1)
I want to subplot on fig_2.
You can access a certain figure by e.g.
ax_1_1 = fig_1.add_subplot(2,2,1)
but this has a slightly different syntax (compare plt.subplot() against fig.add_subplot())
So I would recommend to create figures with subplots already prepared vis plt.subplots which returns handles for figure and axes on the fly:
fig_1, axs_1 = plt.subplots(2, 2)
fig_2, axs_2 = plt.subplots(3, 4)
axs_1[0, 0].plot(range(10))
axs_2[2, 3].plot(range(100))
fig_1.suptitle('Figure 1')
fig_2.suptitle('Figure 2')
etc. ...
You can use figure.add_subplot which will return an ax linked to your figure on which you can plot your data. Look at this page to get a global view of the different objects used by matplotlib.

Update Existent Matplotlib Subplot with a user input

I am currently trying to implement a 'zoom' functionality into my code. By this I mean I would like to have two subplots side by side, one of which contains the initial data and the other which contains a 'zoomed in' plot which is decided by user input.
Currently, I can create two subplots side by side, but after calling for the user input, instead of updating the second subplot, my script is creating an entirely new figure below and not updating the second subplot. It is important that the graph containing data is plotted first so the user can choose the value for the input accordingly.
def plot_func(data):
plot_this = data
plt.close('all')
fig = plt.figure()
#Subplot 1
ax1 = fig.add_subplot(1,2,1)
ax1.plot(plot_this)
plt.show()
zoom = input("Where would you like to zoom to: ")
zoom_in = plot_this[0:int(zoom)]
#Subplot 2
ax2 = fig.add_subplot(1,2,2)
ax2.plot(zoom_in)
plt.show()
The code above is a simplified version of what I am hoping to do. Display a subplot, and let the user enter an input based on that subplot. Then either edit a subplot that is already created or create a new one that is next to the first. Again it is crucial that the 'zoomed in' subplot is alongside the first opposed to below.
I think it is not very convenient for the user to type in numbers for zooming. The more standard way would be mouse interaction as already provided by the various matplotlib tools.
There is no standard tool for zooming in a different plot, but we can easily provide this functionality using matplotlib.widgets.RectangleSelector as shown in the code below.
We need to plot the same data in two subplots and connect the RectangleSelector to one of the subplots (ax). Every time a selection is made, the data coordinates of the selection in the first subplot are simply used as axis-limits on the second subplot, effectiveliy proving zoom-in (or magnification) functionality.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import RectangleSelector
def onselect(eclick, erelease):
#http://matplotlib.org/api/widgets_api.html
xlim = np.sort(np.array([erelease.xdata,eclick.xdata ]))
ylim = np.sort(np.array([erelease.ydata,eclick.ydata ]))
ax2.set_xlim(xlim)
ax2.set_ylim(ylim)
def toggle_selector(event):
# press escape to return to non-zoomed plot
if event.key in ['escape'] and toggle_selector.RS.active:
ax2.set_xlim(ax.get_xlim())
ax2.set_ylim(ax.get_ylim())
x = np.arange(100)/(100.)*7.*np.pi
y = np.sin(x)**2
fig = plt.figure()
ax = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
#plot identical data in both axes
ax.plot(x,y, lw=2)
ax.plot([5,14,21],[.3,.6,.1], marker="s", color="red", ls="none")
ax2.plot(x,y, lw=2)
ax2.plot([5,14,21],[.3,.6,.1], marker="s", color="red", ls="none")
ax.set_title("Select region with your mouse.\nPress escape to deactivate zoom")
ax2.set_title("Zoomed Plot")
toggle_selector.RS = RectangleSelector(ax, onselect, drawtype='box', interactive=True)
fig.canvas.mpl_connect('key_press_event', toggle_selector)
plt.show()
%matplotlib inline
import mpld3
mpld3.enable_notebook()

Matplotlib: data being plotted over legend when using twinx

I'm trying to use Python and Matplotlib to plot a number of different data sets. I'm using twinx to have one data set plotted on the primary axis and another on the secondary axis. I would like to have two separate legends for these data sets.
In my current solution, the data from the secondary axis is being plotted over the top of the legend for the primary axis, while data from the primary axis is not being plotted over the secondary axis legend.
I have generated a simplified version based on the example here: http://matplotlib.org/users/legend_guide.html
Here is what I have so far:
import matplotlib.pyplot as plt
import pylab
fig, ax1 = plt.subplots()
fig.set_size_inches(18/1.5, 10/1.5)
ax2 = ax1.twinx()
ax1.plot([1,2,3], label="Line 1", linestyle='--')
ax2.plot([3,2,1], label="Line 2", linewidth=4)
ax1.legend(loc=2, borderaxespad=1.)
ax2.legend(loc=1, borderaxespad=1.)
pylab.savefig('test.png',bbox_inches='tight', dpi=300, facecolor='w', edgecolor='k')
With the result being the following plot:
As shown in the plot, the data from ax2 is being plotted over the ax1 legend and I would like the legend to be over the top of the data. What am I missing here?
Thanks for the help.
You could replace your legend setting lines with these:
ax1.legend(loc=1, borderaxespad=1.).set_zorder(2)
ax2.legend(loc=2, borderaxespad=1.).set_zorder(2)
And it should do the trick.
Note that locations have changed to correspond to the lines and there is .set_zorder() method applied after the legend is defined.
The higher integer in zorder the 'higher' layer it will be painted on.
The trick is to draw your first legend, remove it, and then redraw it on the second axis with add_artist():
legend_1 = ax1.legend(loc=2, borderaxespad=1.)
legend_1.remove()
ax2.legend(loc=1, borderaxespad=1.)
ax2.add_artist(legend_1)
Tribute to #ImportanceOfBeingErnest :
https://github.com/matplotlib/matplotlib/issues/3706#issuecomment-378407795

plotting 2 graph in same window using matplotlib in python

I was plotting a line graph and a bar chart in matplotlib and both individually were working fine with my script.
but i'm facing a problem:
1. if i want to plot both graphs in the same output window
2. if i want to customize the display window to 1024*700
in 1 st case I was using subplot to plot two graphs in same window but i'm not being able to give both graphs their individual x-axis and y-axis names and also their individual title.
my failed code is:
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
xs,ys = np.loadtxt("c:/users/name/desktop/new folder/x/counter.cnt",delimiter = ',').T
fig = plt.figure()
lineGraph = fig.add_subplot(211)
barChart = fig.add_subplot(212)
plt.title('DISTRIBUTION of NUMBER')
lineGraph = lineGraph.plot(xs,ys,'-') #generate line graph
barChart = barChart.bar(xs,ys,width=1.0,facecolor='g') #generate bar plot
plt.grid(True)
plt.axis([0,350,0,25]) #controlls axis for charts x first and then y axis.
plt.savefig('new.png',dpi=400)
plt.show()
but with this I am not being able to mark both graphs properly.
and also please site some idea about how to resize the window to 1024*700.
When you say
I was using subplot to plot two graphs in same window but i'm not being able to give both graphs their individual x-axis and y-axis names and also their individual title.
do you mean you want to set axis labels? If so try using lineGraph.set_xlabel and lineGraph.set_ylabel. Alternatively, call plt.xlabel and plot.ylabel just after you create a plot and before you create any other plots. For example
# Line graph subplot
lineGraph = lineGraph.plot(xs,ys,'-')
lineGraph.set_xlabel('x')
lineGraph.set_ylabel('y')
# Bar graph subplot
barChart = barChart.bar(xs,ys,width=1.0,facecolor='g')
barChart.set_xlabel('x')
barChart.set_ylabel('y')
The same applies to the title. Calling plt.title will add a title to the currently active plot. This is the last plot that you created or the last plot you actived with plt.gca. If you want a title on a specific subplot use the subplot handle: lineGraph.set_title or barChart.set_title.
fig.add_subplot returns a matplotlib Axes object. Methods on that object include set_xlabel and set_ylabel, as described by Chris. You can see the full set of methods available on Axes objects at http://matplotlib.sourceforge.net/api/axes_api.html.

Categories