matplotlib 如何将海运中的图例设置为自动调整,并使其格式规范化

jtjikinw  于 2023-05-23  发布在  其他
关注(0)|答案(1)|浏览(153)

如何调整图片中的图表图例?,我希望数字采用自定义格式,如[5,000,000]|一千万|15,000,000]或[5m| 10米|15m]或[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()

Chart 1
到目前为止,我能够找到一个工作左右,但我将不得不这样做手动,我想避免

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()

Chart 2

webghufk

webghufk1#

您可以使用FuncFormatter自定义原始图例的get_texts返回的 Texts:

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

相关问题