英文:
How to set legend in seaborn to be automatic adjust with a standardize format
问题
[图表 1](https://i.stack.imgur.com/dFcPl.png)
[图表 2](https://i.stack.imgur.com/jyQIO.png)
英文:
How do i adjust the chart legend in the picture?, i want the number to be in custom format such as
[5,000,000 | 10,000,000 | 15,000,000] or [5m | 10m | 15m] or [0.5 | 1.0 | 1.5]
plt.figure(figsize=(8,4), dpi=200)
# set styling on a single chart
with sns.axes_style('darkgrid'):
ax = sns.scatterplot(data=data_clean,
x='USD_Production_Budget',
y='USD_Worldwide_Gross',
hue='USD_Worldwide_Gross',
size='USD_Worldwide_Gross')
ax.set(ylim=(0, 3000000000),
xlim=(0, 450000000),
ylabel='Revenue in $ billions',
xlabel='Budget in $100 millions')
plt.show()
So far, i was able to find a work around but i would have to do it manually, which i would like to avoid
plt.figure(figsize=(8,4), dpi=200)
# set styling on a single chart
with sns.axes_style('darkgrid'):
ax = sns.scatterplot(data=data_clean,
x='USD_Production_Budget',
y='USD_Worldwide_Gross',
hue='USD_Worldwide_Gross',
size='USD_Worldwide_Gross')
ax.set(ylim=(0, 3000000000),
xlim=(0, 450000000),
ylabel='Revenue in $ billions',
xlabel='Budget in $100 millions')
plt.legend(title='World_Wide_Gross',loc='upper left',labels=[0,0.5,1.0,1.5,2.0,2.5])
plt.show()
答案1
得分: 0
你可以使用 FuncFormatter
来自定义原始图例的 get_texts
返回的 Text:
f = lambda x, _: "0m" if x == 0 else f"{x / 1e8:.0f}m" # / 1e6 would make more sense ?
#f = lambda x, _: 0 if x ==0 else x / 1e9 # uncomment this line to choose the 2nd format
fmt = plt.FuncFormatter(f)
for text in ax.legend().get_texts():
text.set_text(fmt(float(text.get_text())))
ax.legend().set_title("World_Wide_Gross")
输出:
使用的输入:
np.random.seed(123456)
data_clean = pd.DataFrame({
"USD_Production_Budget": np.random.uniform(0, 4.5e8, 100),
"USD_Worldwide_Gross": np.random.uniform(0, 3e9, 100)}
)
data_clean.loc[5] = 0
英文:
You can use a FuncFormatter
to customize the Texts returned by get_texts
of the original legend :
f = lambda x, _: "0m" if x == 0 else f"{x / 1e8:.0f}m" # / 1e6 would make more sense ?
#f = lambda x, _: 0 if x ==0 else x / 1e9 # uncomment this line to choose the 2nd format
fmt = plt.FuncFormatter(f)
for text in ax.legend().get_texts():
text.set_text(fmt(float(text.get_text())))
ax.legend().set_title("World_Wide_Gross")
Output :
Input used :
np.random.seed(123456)
data_clean = pd.DataFrame({
"USD_Production_Budget": np.random.uniform(0, 4.5e8, 100),
"USD_Worldwide_Gross": np.random.uniform(0, 3e9, 100)}
)
data_clean.loc[5] = 0
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论