Legend in Seaborn Scatter plot: How to limit the number of decimal places? - format

Is there a way to limit the number of decimal places in the legend of a seaborn scatter plot?
here is the code I have written so far. Cannot find a way to format the number in the legend (set by the variable z)
fig, ax0 = plt.subplots()
sns.scatterplot(x='x',
y='y',
data=df,
size='z',
sizes=(50, 300),
size_norm=(0,0.5),
palette=custom_palette,
ax=ax0
)
ax0.set(xscale='log')
plt.show()

Related

How I can plot colored scale in plot in R studio without ggplot package?

Hi, Any idea how i could create plot like the attached one.it is scatter plot for xdata and y data and the color is based on values of the third column.I would like not to use ggplot only basic R and I am not able to produce the scale thanks. I tried to read the data frame and drfine the y and x and make the scatterplot, color the points df<-AllData
y<- AllData $column1
x<- AllData $column2
LINEAR REGRESSION
reg<-lm(y ~ x, data = AllData )
plot(x,y, type="p", pch=20,ylab="",xlab="",axes=F,ylim = c(0,80),xlim=c(0,80),cex=1,col=ifelse(AllData$column3<10, 'blueviolet',ifelse(AllData$column3<20, 'blue4',ifelse(AllData$column3<30, 'blue2',ifelse(AllData$column3<100, 'darkgoldenrod', 'red'...etc till 100))))

Flip over colorbar of Seaborn heatmap

I am trying to flip over the colorbar of my Heatmap in Seaborn.
Here is how it looks at the moment.
What I would like to have is the colorbar starting from the top
with the value 0 (Green) and going to the bottom with the value 8 (red).
Please note that the Y-axis points are sorted based on the average values
from min (top) to max (bottom) and I would like to keep them this way.
Any idea if it is possible to do that?
Here is an example of the current code:
cmap1 = mcolors.LinearSegmentedColormap.from_list("n",['#00FF00','#12FF00','#24FF00','#35FF00','#47FF00','#58FF00','#6AFF00','#7CFF00','#8DFF00','#9FFF00','#B0FF00','#C2FF00','#D4FF00','#E5FF00','#F7FF00','#FFF600','#FFE400','#FFD300','#FFC100','#FFAF00','#FF9E00','#FF8C00','#FF7B00','#FF6900','#FF5700','#FF4600','#FF3400','#FF2300','#FF1100','#FF0000',])
plt.figure(figsize=(22, 12))
df = pd.DataFrame( AgainReorderindSortedEDPList, index=sortedProgrammingLanguagesBasedOnAverage, columns=sortedTasksBasedOnAverage)
mask = df.isnull()
sns.heatmap(df, annot=True, fmt="g", cmap=cmap1, mask=mask)
plt.yticks(fontsize = 12)
plt.yticks(rotation=0)
plt.xticks(fontsize = 11)
plt.ylabel('Programming Languages', size = 15)
plt.xlabel('Programming Tasks', size = 15)
plt.xticks(rotation=-45)
plt.show()
The AgainReorderindSortedEDPList, sortedProgrammingLanguagesBasedOnAverage, and sortedTasksBasedOnAverage
are the data I am using to plot this heatmap.
You simply need to call invert_yaxis() on the axes that contain the colorbar. How to do that depends a bit on how you are creating your heatmap, but unfortunately you have not provided your code.
Here is the most simple example:
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data)
plt.gcf().axes[1].invert_yaxis()
plt.gcf() gets a reference to the current figure. Figure.axes is a list of axes in the figure. axes[1] is the second axes, which should correspond to the axes created by heatmap to plot the colorbar.

Seaborn Heatmap Axis Format reverses Graph

When I add in the formatting of the x axis, the graph remains the same. When I format the y axis tick labels, the graph reverses and I can't figure out why.
Heatmap before y-axis format
Here is the graph after the x-axis format
ax = sns.heatmap(All_new, linewidths=.5, annot=True, cmap="RdYlGn")
plt.tight_layout()
plt.xlabel('Losing Digit')
plt.ylabel('Winning Digit')
plt.title('Total Distribution of Final Digits (%)')
ax.get_xaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x))))
ax.get_yaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x))))
#ax.invert_yaxis()
plt.show()

Seaborn Stripplot Axis Values with Correct Scaling

I'm trying to plot some data in seaborn where the x values are percentages*100 as floating point numbers (ie 90.909). When I make the plot:
fig, ax = plt.subplots(figsize=(10,10))
ax = sns.stripplot(df_12['% ident'], df_12['length'], jitter=True)
The decimals in the floating points make the X axis unreadable:
Initial Plot
I would like to set the x axis to show only whole number multiples of 5 (ie 80, 85, 90, 95, 100).
One method I have tried is the following:
fmt = '{:0.0f}'
xticklabels = []
count = 0
for item in ax.get_xticklabels():
count+= 1
item.set_text(fmt.format(float(item.get_text())));
xticklabels += [item];
ax.set_xticklabels(xticklabels);
This succeeds in changing the axis values to integers, but the axis looks busy. The numbers shown are also inconsistent between similar datasets.
Second Plot
I would like to reduce the total number of values shown on the axis. I have tried to use
ax.xaxis.set_major_locator(plt.MaxNLocator(5))
Or similarly
ax.xaxis.set_major_locator(plt.MaxNLocator(5))
ax.set_xticklabels([80, 85, 90, 95, 100])
Which give outputs similar to this:
Third Plot
If you compare this to the previous plot, you'll notice the x axis labels no longer relate to the points plotted. How do I set the values of the x axis while still keeping them related to the points plotted?
Other things I have tried:
ax.set_xlim(75, 100)
This and any variants result in a blank plot.
ax.set(xticklabels=[75,80,85,90,95,100])
Does the same thing where the axis labels don't match the data.
ax.set(xticks=range(75,101), xticklabels=[75,80,85,90,95,100])
Results in all the data points stuck on the left side of the plot with all the axis labels overlapping on a single tick on the right.
ax.xaxis.set_major_locator(ticker.MaxNLocator(integer=True))
This doesn't change the axis values to integers, and also appears to cause the axis to no longer correlate with the data.

matplotlib: histogram and bin labels

I'm trying to plot a histogram with bar chart, and I'm having difficulties figuring out how to align the x-axis labels with the actual bins. The code below generates the following plot:
as you can see, the end of each x-label is not aligned to the center of its bin. The way i'm thinking about this is: when i apply a 45-degree rotation, the label pivots around its geometrical center. I was wondering if it's possible to move the pivot up to the top of the label. (Or simply translate all the labels slightly left.)
import matplotlib.pyplot as plt
import numpy as np
#data
np.random.seed(42)
data = np.random.rand(5)
names = ['A:GBC_1233','C:WERT_423','A:LYD_342','B:SFS_23','D:KDE_2342']
ax = plt.subplot(111)
width=0.3
bins = map(lambda x: x-width/2,range(1,len(data)+1))
ax.bar(bins,data,width=width)
ax.set_xticks(map(lambda x: x, range(1,len(data)+1)))
ax.set_xticklabels(names,rotation=45)
plt.show()
Use:
ax.set_xticklabels(names,rotation=45, rotation_mode="anchor", ha="right")
The output is:

Resources