How can I use alpha with seaborn.pointplot? [duplicate] - python

I want to make a seaborn pointplot that has transparency so that I can clearly see the points located behind others of a different color.
I tried adding "alpha=0.3" to the call to pointplot and also tried the same within a catplot with kind='point'; however, neither of these results in the desired transparency (no error message is produced either).
sns.pointplot(x='aamm', y='posrate', hue='AA:XX', hue_order=[1,0], data=data, dodge=True, palette=palette, alpha=0.3)
I was hoping to get a plot with transparent points, but instead, I got one with normal opaque points. The dodge option doesn't seem to produce any noticeable effect either, in terms of separating overlapping points of different color.
Is there a way to add transparency to a seaborn pointplot or use something else to get a similar effect?
Thank you.

To the extent of my knowledge there is no more an alpha parameter that can be directly set in seaborn.
You can do the following thou:
Sample dataframe
df = pd.DataFrame(np.random.randint(low=0, high=1000, size=(50, 5)))
Plotting
ax = sns.pointplot(x=0, y=1, data=df, dodge=True,plot_kws=dict(alpha=0.3))
plt.setp(ax.collections, alpha=.3) #for the markers
plt.setp(ax.lines, alpha=.3) #for the lines

Related

Seaborn lineplot without lines between points

How can I use the lineplot plotting function in seaborn to create a plot with no lines connecting between the points. I know the function is called lineplot, but it has the useful feature of merging all datapoints with the same x value and plotting a single mean and confidence interval.
tips = sns.load_dataset('tips')
sns.lineplot(x='size', y='total_bill', data=tips, marker='o', err_style='bars')
How do I plot without the line? I'm not sure of a better way to phrase my question. How can I plot points only? Lineless lineplot?
I know that seaborn has a pointplot function, but that is for categorical data. In some cases, my x-values are continuous values, so pointplot would not work.
I realize one could get into the matplotlib figure artists and delete the line, but that gets more complicated as the amount of stuff on the plot increases. I was wondering if there are some sort of arguments that can be passed to the lineplot function.
To get error bars without the connecting lines, you can set the linestyle parameter to '':
import seaborn as sns
tips = sns.load_dataset('tips')
sns.lineplot(x='size', y='total_bill', data=tips, marker='o', linestyle='', err_style='bars')
Other types of linestyle could also be interesting, for example "a loosely dotted line": sns.lineplot(..., linestyle=(0, (1, 10)))
I recommend setting join=False.
For me only join = True works.
sns.pointplot(data=df, x = "x_attribute", y = "y_attribute", ci= 95, join=False)

matplotlib hatched and filled histograms

I would like to make histograms that are both hatched and filled (like these bar plots on the left in this matplotlib example):
Here's the code I tried to use:
import matplotlib.pyplot as plt
plt.hist(values, bins, histtype='step', linewidth=2, facecolor='c', hatch='/')
But no matter whether I specify "facecolor" or "color", only the lines of the hatching appear in colour and the histogram is still unfilled. How can I make the hatching show up on top of a filled histogram?
In order to fill the area below the histogram the kwarg fill can be set to True. Then, the facecolor and edgecolor can be set in order to use different colors for the hatch and the background.
plt.hist(np.random.normal(size=500), bins=10, histtype='step', linewidth=2, facecolor='c',
hatch='/', edgecolor='k',fill=True)
This generates the following output:
histtype='step'draws step lines. They are by definition not filled (because they are lines.
Instead, use histtype='bar' (which is the default, so you may equally leave it out completely).

How do I set matplotlib plot to "no fill"?

I'd like to superimpose one plot over another (they are polygons, really in some lat/lon space, using geopandas, but the plot is simply derived from matplotlib)
I have:
figZ, axZ = plt.subplots(1, figsize=(11,8.5))
Sfig = X.plot(ax=axZ, color='white', edgecolor='black', lw=0.7)
Y.plot(ax=axZ, color='white', edgecolor='black', lw=0.7, alpha=0.3)
How do I set Sfig's color to "no-fill" instead of white? The way it is now it "blurs" my Sfig image (X.plot) by the alpha of the Y.plot one. How do I set "color" to actually transparent?
I don't expect upvotes, but this is what I found as solution. I'll vote up better ones if they exist:
Sfig = X.plot(ax=axZ, facecolor="none",
edgecolor='black', lw=0.7)
I know this post doesn't mention seaborn, but I suspect a lot of people end up here asking this question for seaborn also (as I did).
The top answer almost works for seaborn boxplots, you just need to pass it as boxprops.
sns.boxplot(data=data, x=x, y=y, hue=hue, boxprops=dict(facecolor="none"))
NOTE: I emphasise that this solution only works for boxplots. There is an open, more general, feature request for this functionality in seaborn.
To disable facecolor just set with the value (0, 0, 0, 0), i.e.,
Sfig = set_facecolor((0,0,0,0))

Python- How to make colorbar orientation horizontal?

So I have a plot with a basemap, a colormesh on top, and a colorbar set to cbar. I want the colorbar orientation to be horizontal instead of vertical, but when I set orientation='horizontal' in the cbar=m.colorbar line after extend='max', I get the following error: "colorbar() got multiple values for keyword argument 'orientation'"
Someone on another question explained why this happens, but I honestly couldn't understand the answer or see an explanation of how to fix it. Can someone help? I tried using plt.colorbar instead, but for some reason that doesn't accept my tick settings.
Here's what my plot looked like before...
#Set cmap properties
bounds = np.array([0.1,0.2,0.5,1,2,3,4,6,9,13,20,30])
norm = colors.LogNorm(vmin=0.1,vmax=30) #creates logarithmic scale
#Create basemap
fig = plt.figure(figsize=(15.,10.))
m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,llcrnrlon=0,urcrnrlon=360.,lon_0=180.,resolution='c')
m.drawcoastlines(linewidth=1)
m.drawcountries(linewidth=1)
m.drawparallels(np.arange(-90,90,30.),linewidth=0.3)
m.drawmeridians(np.arange(-180.,180.,90.),linewidth=0.3)
meshlon,meshlat = np.meshgrid(lon,lat)
x,y = m(meshlon,meshlat)
#Plot variables
trend = m.pcolormesh(x,y,lintrends_36,cmap='jet', norm=norm, shading='gouraud')
#Set plot properties
plt.tight_layout()
#Colorbar
cbar=m.colorbar(trend, size='3%',ticks=bounds,extend="max") #THIS LINE
cbar.set_label(label='Linear Trend (mm/day/decade)',size=30)
cbar.set_ticklabels(bounds)
#Titles & labels
plt.suptitle('Linear Trends of Precipitation (CanESM2)',fontsize=40,y=0.962)
plt.title('a) 1979-2014',fontsize=40)
plt.ylabel('Latitude',fontsize=30)
plt.show()
When orientation is attempted (all other code being the same)...
And the map looks like this.
You need to use location="bottom"
cbar=m.colorbar(trend, size='3%',ticks=bounds,extend="max",location="bottom")
I got that from this example in the basemap documentation.
As others have already stated in the comments
plt.colorbar(orientation='horizontal')
is an alternative (simpler) solution!

Matplotlib center alignment for pie chart labels

I have produced a very simple pie chart in Python using Matplotlib and I am wanting to edit the alignment of my labels. I have used \n within my labels to split the line as the labels are too long for one line. But as you can see from the picture called 'pie chart image', it's a mix of weird alignments at the moment. I would really like to have it center alignment.
For other chart/graph types in Matplotlib there is an argument called align where you can set it to center, however, plt.pie(...) does not seem to have this attribute.
Here is my code:
import matplotlib.pyplot as plt
k = [7,15]
labels = 'Strongly and Mostly \n Agree', 'Strongly/Mostly Disagree \n and In the Middle'
plt.pie(k, labels= labels)
plt.show()
Any ideas?
You can pass a dictionary of text properties to plt.pie via the textprops argument. For example:
plt.pie(k, labels=labels, textprops={'weight': 'bold'})
However, if you try to specify the horizontalalignment property, you'll get an error saying that you provided that parameter twice. Obviously you didn't, but matplotlib passed both it's hard-coded value and your value to some internal function.
But that's probably a good thing. The way I see it, there's not so much a mix of alignments, but a consistent alignment of the text against the pie.
Back to your question
pie returns both the patches and the labels for each wedge. So you can loop through the labels after your initial call to pie to modify their alignment. That looks like this:
k = [7, 15]
labels = 'Strongly and Mostly\nAgree', 'Strongly/Mostly Disagree\nand In the Middle'
fig, ax = plt.subplots()
ax.set_aspect('equal')
wedges, labels = ax.pie(k, labels=labels, textprops={'weight': 'bold'})
for label in labels:
label.set_horizontalalignment('center')
As you can see, the labels now overlap with the wedges, diminishing legibility.
The labels also have a set_position method (i.e., label.set_position((x, y))), but recomputing the positions for N labels in a pie chart sounds like a Bad Time to me.

Categories

Resources