trying to save the figure of stacked bar chart in canvas widget - python

I grouped the data and tried for a stacked bar chart and it worked fine the figure is also plotted in the interpreter with an ipynb jupyter notebook file as show in the picture attached, but when I want to use that figure in the canvas of matplotlib.backends canvas for displaying plots figure was not plotted just empty axes,
need some solution to save the subplot and utilize it for displaying in canvas
can any share their knowledge with me to solve my problem
dfd = df.groupby(['Region','Sub-Category']).aggregate({'Sales':sum}).unstack(-2)
fig, ax = plt.subplots(figsize =(7, 5))
below is the core detailed code
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_excel("C:/Users/OneDrive/Desktop/Excel_files/Sample - Superstore2.xlsx")
df.groupby(['Category','Sub-Category']).aggregate({'Sales':sum}).unstack(-2).plot(kind = 'bar',stacked= True,figsize = (15,7) )
plt.show()
this is my full code what I want is like I to want use its figure to display in the Tkinter canvas widget, as like we have option in below possible way as far as my knowledge
fig, ax = plt.subplots(1, figsize=(7, 5))
by using ax we will plot graphs and those graphs will be stored in fig variable as subplots and this fig variable can be used to display the figure in canvas.
type of fig varibale is -> <class 'matplotlib.figure.Figure'>
but when i use ax for plotting the stacked bar plot its not been plotted properly

Related

Show only the last plot in Python using MatPlotLib

I am using Python 3.5 with MatPlotLib package. My problem is as follows:
I generate, say 50 plots, which I save each to a PNG file. Then I generate 2 summarizing plots, which I want to both save and show on display. However, when I use the plt.show() command, it also shows all the previous 50 plots, which I don't want to display, just save them. How to suppress the show on these previous 50 plots and show only the last one?
Here is an example code:
import matplotlib.pyplot as plt
import numpy as np
for i in range(50):
fig = plt.figure()
plt.plot(np.arange(10),np.arange(10)) # just plot something
plt.savefig(f"plot_{i}.png")
# I want to save these plots but not show them
# summarizing plot
fig = plt.figure()
plt.plot(np.arange(100),np.arange(100))
plt.show() # now it shows this fig and the previous 50 figs, but I want only to show this one!
Close all after the loop:
plt.close("all") #this is the line to be added
fig = plt.figure()
plt.plot(np.arange(100),np.arange(100))
plt.show()

matplotlib colorbar update/remove destroys axes layout

I have matplotlib embedded in a tkinter gui. With the seaborn heatmap function, I create a heatmap and a colorbar which works as I want it to when creating the first plot. However, if I plot again, this will not overwrite the colorbar but add another colorbar to my figure. I end up with to many colorbars this way.
The figure I create for the plot contains two axes:
[<matplotlib.axes._subplots.AxesSubplot object at 0x000001F36C8C3390>, <matplotlib.axes._subplots.AxesSubplot object at 0x000001F36D6ABF98>]
the first one is the plot itself and the second the colorbar and looks like this:
plot 1
If I plot again, the result is:
plot 2
Simply deleting the colorbar with
self.fig.axes[1].remove()
before creating the next plot doesn't do the trick because it will just remove the colorbar but the layout of the plot keeps shrinking:
plot 3
plot 4
Note that the figure size stays the same but the size of the plot keeps getting smaller when I plot again and the colorbar moves futher to the left while the entire right part of the plot stays white.
As I create a tkinter gui, the ploting window is initialized when the program is first run.
self.fig = plt.figure.Figure( facecolor = "white", figsize = (7,4))
self.ax = self.fig.subplots()
self.x_data = x_data
self.y_data = y_data
when somebody presses a plot button the plot is created
def plot_on_plotframe(self):
self.ax.cla()
#executes required matplotlib layout
self.plotlayout[self.plot_type]()
print('plottype: {}'.format(self.plot_type))
#print('Plot xdata: {}'.format(self.x_data))
self.canvas.draw()
I need to make different types of plot and the proper type is selected by plotlayout:
self.ax = sns.heatmap(self.x_data, vmin=self.settings[2][0], vmax=self.settings[2][1], cmap='viridis', fmt=self.settings[0], annot=self.settings[1], linewidths=0.5, annot_kws={'size': 8}, ax = self.ax)
self.ax.set_xticklabels(self.ax.get_xticklabels(), rotation=0)
self.fig.tight_layout()
It would be fantastic if somebody could tell me why matplotlib messes with the layout even after I delete the old colorbar in the first place. I think this has something to do with the gridSpec but I don't get how I tell matplotlib to reset the layout properly. Also any other suggestions on how to resovle this?
Thanks in advance

How do I set the matplotlib window size for the MacOSX backend?

I have a python plotting function that creates a grid of matplotlib subplots and I want the size of the window the plots are drawn in to depend on the size of the subplot grid. For example, if the subplots grid is 5 rows by 5 columns (25 subplots) the window size needs to be bigger than one where there is only 5 subplots in a single column. I'm not sure how to control the window size matplotlib creates plots in. Can someone tell me how to control the plot window size for matplotlib using the MacOSX backend?
For all backends, the window size is controlled by the figsize argument.
For example:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(5, 5, figsize=(12, 10))
plt.show()
If you're creating the figure and subplots separately, you can specify the size to plt.figure (This is exactly equivalent to the snippet above):
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(12, 10))
for i in range(1, 26):
fig.add_subplot(5, 5, i)
plt.show()
In general, for any matplotlib figure object, you can also call fig.set_size_inches((width, height)) to change the size of the figure.

Multiple pie charts using matplotlib

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.

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