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.
Related
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
I'm trying to get two graphs into the same fig, using different y-axes, and it works fine when I use the same kind of plot (two barplots or two lineplots, for example). Using this code
fig, graph = plt.subplots(figsize=(75,3))
sns.lineplot(x='YearBuilt',y='SalePrice',ax=graph,data=processed_data,color='red')
graph2 = graph.twinx()
sns.lineplot(x='YearBuilt', y='AvgOverallQual',ax=graph2,data=processed_data,color='teal')
I obtain this
But when I try to use different kinds, like this:
fig, graph = plt.subplots(figsize=(75,3))
sns.barplot(x='YearBuilt',y='SalePrice',ax=graph,data=processed_data,color='red')
graph2 = graph.twinx()
sns.lineplot(x='YearBuilt', y='AvgOverallQual',ax=graph2,data=processed_data,color='teal')
my graph looks like:
How do I overlay different kinds of graph in Seaborn?
A seaborn barplot is a categorical plot. The first bar will be at position 0, the second at position 1 etc. A lineplot is a numeric plot; it will put all points at a position given by the numeric coordinates.
Here, it seems there is no need to use seaborn at all. Since matplotlib bar plots are numerical as well, doing this in matplotlib alone will give you the desired overlay
fig, ax = plt.subplots(figsize=(75,3))
ax.bar('YearBuilt','SalePrice', data=processed_data, color='red')
ax2 = ax.twinx()
ax2.plot('YearBuilt', 'AvgOverallQual', data=processed_data, color='teal')
Ive created a simple histogram/KDE plot with seaborn and Im trying to add custom labels to the x-axis as follows:
plt.title("Cond Density")
plt.xlabel("Cond")
plt.ylabel("Density")
plt.xticks = (['Bob','Alex','Steve','Gwen','Darren'])
sns.distplot(rawData['Conditions'], bins=20)
sns.kdeplot(rawData['Conditions'], shade=True)
plt.show()
There are only 5 int elements in rawData['Conditions'], but the x-axis justs reflects the values in rawData['Conditions'], which are just [0,1,2,3,4].
What am I missing?
Histograms need sequential ticks. I'm unsure as to what you're exactly trying to plot, but if you want to graph the density relative to each of these names, a bar graph would be best.
In this bar chart:
How do I make the x-axis labels appear in the bars of the bar-chart and left-aligned with the x-axis?
I tried the ax.xaxis.labelpad() method but it does not seem to do anything.
you can set the y location of the ticks when you call set_xticklabels. So, if you set y to something small but positive, it should be placed inside the bars.
For example:
import matplotlib.pyplot as plt
fig,ax = plt.subplots(1)
ax.bar([0,1,2,3],[7900,9400,8700,9990],facecolor='#5080B0',edgecolor='k',width=0.3)
ax.set_xticks([0.15,1.15,2.15,3.15])
ax.set_xticklabels(['beek1','beek2','orbath','Kroo'],
rotation='vertical',y=0.05,va='bottom')
Produces the following plot:
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.