【问题标题】:How do I change the units shown on the x-axis labels on a Matplotlib bar chart如何更改 Matplotlib 条形图 x 轴标签上显示的单位
【发布时间】:2021-09-14 15:42:54
【问题描述】:

我正在努力做到这一点,因此 x 轴上的收入刻度将价值显示为一百万的因子,而不是像现在这样的一亿因子。我似乎无法弄清楚如何做到这一点。我的代码和生成的条形图如下。

import numpy as np
import pandas as pd
import matplotlib.ticker as plticker
import matplotlib.pyplot as plt
import seaborn as sns
from IPython.display import display
from pandas import Series

%matplotlib inline


# Define Figure Size
fig, ax = plt.subplots(figsize=(25,25))

# Get the average vote_average for each genre
average_revenue = df2.groupby('release_year')['revenue_adj'].mean()

# Find positions of y ticks
y_pos = np.arange(len(df2['release_year'].unique()))
# Set up Bar Chart
ax.set_yticks(y_pos)
ax.set_yticklabels(sorted(df2['release_year'].unique()))
ax.set_xlabel('Revenue in Millions', fontsize=16)
ax.set_ylabel('Release Year', fontsize=16)
ax.set_title('Revenue by Release Year', fontsize=20)

# Set Size of X and Y labels
plt.rc('xtick', labelsize=14)
plt.rc('ytick', labelsize=14)

# Put Values next to Each Bar
for i, v in enumerate(average_revenue):
    a = v/1000000
    ax.text(v, i, ('$' + str(round(a,2)) + 'M'), color='blue')
    
ax.invert_yaxis()  # labels read top-to-bottom

# Draw Bar Chart
ax.barh(y_pos, average_revenue, align='center', color='green', ecolor='black')

【问题讨论】:

    标签: python pandas numpy matplotlib bar-chart


    【解决方案1】:

    目前,数据以个数显示,而不是数百万或数亿。注意图右侧的1e8。您可以通过将输入除以一百万来绘制以百万为单位的值:

    ax.barh(y_pos, average_revenue * 1e-6, ...)
    

    如果您不想更改数据,也可以调整 x 轴上的 formatter。例如,您可以像这样使用FuncFormatter

    from matplotlib.ticker import FuncFormatter
    
    ax.xaxis.set_major_formatter(FuncFormatter(lambda x, pos: f'{x * 1e-6:0.1f}'))
    

    【讨论】:

      猜你喜欢
      • 2020-03-31
      • 2017-09-26
      • 2021-05-07
      • 2021-12-03
      • 2019-01-28
      • 1970-01-01
      • 1970-01-01
      • 2021-07-24
      • 1970-01-01
      相关资源
      最近更新 更多