[英]How do I squeeze matplotlib bar x-axis labels to drop missing numerical values?
[英]How do I change the units shown on the x-axis labels on a Matplotlib bar chart
我正在努力使收入的 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')
現在,數據以單位顯示,而不是數百萬或數億。 注意圖右側的1e8
。 您可以通過將輸入除以百萬來繪制以百萬為單位的值:
ax.barh(y_pos, average_revenue * 1e-6, ...)
或者,如果您不想更改數據,您可以在 x 軸上調整格式化程序。 例如,您可以像這樣使用FuncFormatter
:
from matplotlib.ticker import FuncFormatter
ax.xaxis.set_major_formatter(FuncFormatter(lambda x, pos: f'{x * 1e-6:0.1f}'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.