Home > Software engineering >  How to get rid of decimal point in the legend
How to get rid of decimal point in the legend

Time:08-24

Here is the code I used to make the visualization:

results = pd.DataFrame(reduced_data,columns=['pca1','pca2','pca3','pca4','pca5','pca6','pca7'])
ax = sns.scatterplot(x="pca1", y="pca2", hue=H12022_full['cluster'],palette=['green','orange','brown','dodgerblue', 'yellow', 'blue', 'red'], data=results)
ax.get_xaxis().set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))
ax.get_yaxis().set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))

This is the result:

enter image description here

I wanted to know how I could get rid of the decimals in the legend. So instead of 1.0 it will be just 1?

CodePudding user response:

You can try this. As the values are in float (1.0, 2.0..) and in text, you will need to convert it to float and then integer... A simple example.

df = pd.DataFrame({'foo':[1,2,3.0,4,5], 'bar': [1,2,3.2,4,5]})
ax = sns.scatterplot(x='foo', y='bar', data=df, hue='foo', palette=['green','orange','brown','dodgerblue', 'yellow'])
l = ax.get_legend_handles_labels()[1]
legend = list(map(round, list(map(float, l))))
plt.legend(legend)

Plot

enter image description here

CodePudding user response:

Can you try the following:

actual_legends = ax.get_legend_handles_labels()[1]
legend = [int(float(l)) for l in actual_legends]
plt.legend(legend)
  • Related