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.
Related
I have a boxplot below (using seaborn) where the "box" part is too squashed. How do I change the scale along the y-axis so that the boxplot is more presentable (ie. the "box" part is too squashed) but still keeping all the outliers in the plot?
Many thanks.
You can do two things here.
Make the plot bigger
Change the range of the y-axis
Since you want to keep the outliers, rescaling the y-axis may not be that effective. You haven't given any data or code examples. So I'll just add a way to make your figure bigger.
# this script makes the figure bigger and rescale the y-axis
ax = plt.figure(figsize=(20,15))
ax = sns.boxplot(x="day", y="total_bill", data=tips)
ax.set_ylim(0,100)
You could set the axis after the plot:
import seaborn as sns
df = sns.load_dataset('iris')
a = sns.boxplot(y=df["sepal_length"])
a.set(ylim=(0,10))
Additionally, you could try dropping outliers from the plot passing showfliers = False in boxplot.
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')
I need to fit a function to a large number of datasets stored in several files and compare the fits. I open a file, read the columns and plot each fit as a subplot after fitting. Eventually I have a figure with lot of subplots showing all the fits. However, I need to see the fit and also the residual for each subplot like in the figure.
So far, I have the following. I thought I could add axes to subplot but it does not work. The function that I have works. But I do not know how to add axes to subplot to plot the residual with the fit as a subplot to the subplot.
def plotall(args):
x=args[0]
ydata=args[1]
chisq=args[2]
fit=args[3]
g1=args[4]
a=args[5]
ptitle=args[6]
axi = fig1.add_subplot(a1,b1,a+1)
axi.plot(x, ydata,'ko',markersize=2,label='Data')
axi.plot(x,fit,'m-',label='Fit')
axi.text(0.75,0.8,'T=%4.1f(K)'%ptitle, fontsize=7,transform = axi.transAxes)
axi.text(0.05,0.45,r'$\chi^2$=%3.1f'%chisq,fontsize=7,transform = axi.transAxes)
ytlist=np.linspace(min(ydata),max(ydata),4)
axi.set_yticks(ytlist)
axi.set_xlim([xlow,xhi])
xtlist=np.linspace(xlow,xhi,6)
axi.set_xticks(xtlist)
for label in (axi.get_xticklabels() + axi.get_yticklabels()):
label.set_fontname('Arial')
label.set_fontsize(5)
axi.legend(('Data','Fit'), 'upper left', shadow=False, fancybox=False,numpoints=1,
frameon = 0,labelspacing=0.01,handlelength=0.5,handletextpad=0.5,fontsize=6)
I use autofmt_xdate to plot long x-axis labels in a readable way. The problem is, when I want to combine different subplots, the x-axis labeling of the other subplots disappears, which I do not appreciate for the leftmost subplot in the figure below (two rows high). Is there a way to prevent autofmt_xdate from quenching the other x-axis labels? Or is there another way to rotate the labels? As you can see I experimented with xticks and "rotate" as well, but the results were not satisfying because the labels were rotated around their center, which resulted in messy labeling.
Script that produces plot below:
from matplotlib import pyplot as plt
from numpy import arange
import numpy
from matplotlib import rc
rc("figure",figsize=(15,10))
#rc('figure.subplot',bottom=0.1,hspace=0.1)
rc("legend",fontsize=16)
fig = plt.figure()
Test_Data = numpy.random.normal(size=20)
fig = plt.figure()
Dimension = (2,3)
plt.subplot2grid(Dimension, (0,0),rowspan=2)
plt.plot(Test_Data)
plt.subplot2grid(Dimension, (0,1),colspan=2)
for i,j in zip(Test_Data,arange(len(Test_Data))):
plt.bar(i,j)
plt.legend(arange(len(Test_Data)))
plt.subplot2grid(Dimension, (1,1),colspan=2)
xticks = [r"%s (%i)" % (a,b) for a,b in zip(Test_Data,Test_Data)]
plt.xticks(arange(len(Test_Data)),xticks)
fig.autofmt_xdate()
plt.ylabel(r'$Some Latex Formula/Divided by some Latex Formula$',fontsize=14)
plt.plot(Test_Data)
#plt.setp(plt.xticks()[1],rotation=30)
plt.tight_layout()
#plt.show()
This is actually a feature of the autofmt_xdate method. From the documentation of the autofmt_xdate method:
Date ticklabels often overlap, so it is useful to rotate them and right align them. Also, a common use case is a number of subplots with shared xaxes where the x-axis is date data. The ticklabels are often long, and it helps to rotate them on the bottom subplot and turn them off on other subplots, as well as turn off xlabels.
If you want to rotate the xticklabels of the bottom right subplot only, use
plt.setp(plt.xticks()[1], rotation=30, ha='right') # ha is the same as horizontalalignment
This rotates the ticklabels 30 degrees and right aligns them (same result as when using autofmt_xdate) for the bottom right subplot, leaving the two other subplots unchanged.
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.