【发布时间】:2022-01-15 01:10:30
【问题描述】:
在使用 groupby 并尝试使用 seaborn 绘图时,我遇到了轴标签问题。这是我的问题:
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
df = pd.DataFrame({'user': ['Bob', 'Jane','Alice','Bob','Jane','Alice'],
'income': [40000, 50000, 42000,47000,53000,46000]})
groupedProduct = df.groupby(['Product']).sum().reset_index()
然后我使用 seaborn 绘制水平条形图:
bar = sns.barplot( x="income", y="user", data=df_group_user, color="b" )
#Prettify the plot
bar.set_yticklabels( bar.get_yticks(), size = 10)
bar.set_xticklabels( bar.get_xticks(), size = 10)
bar.set_ylabel("User", fontsize = 20)
bar.set_xlabel("Income ($)", fontsize = 20)
bar.set_title("Total income per user", fontsize = 20)
sns.set_theme(style="whitegrid")
sns.set_color_codes("muted")
不幸的是,当我以这种方式运行代码时,y 轴刻度标记为 0、1、2,而不是我希望的 Bob、Jane、Alice。
如果我按以下方式使用 matplotlib,我可以解决这个问题:
df_group_user = df.groupby(['user']).sum()
df_group_user['income'].plot(kind="barh")
plt.title("Total income per user")
plt.ylabel("User")
plt.xlabel("Income ($)")
理想情况下,我想使用 seaborn 进行绘图,但如果我不像上面那样使用 reset_index(),那么在调用 sns.barplot 时:
bar = sns.barplot( x="income", y="user", data=df_group_user, color="b" )
ValueError: Could not interpret input 'user'
【问题讨论】:
-
您好,非常感谢您的回复,我无法共享输入数据,但我使用更简单的数据框重现了该问题。我现在正在编辑问题,以便更清楚问题是什么。
-
嗨@JohanC,我查了一下,它是'0.11.1'
-
@Mr.T:我现在已经用我使用的所有代码代码和一个可以轻松复制的数据框更新了这个问题。希望没事。
-
您使用
bar.set_yticklabels( bar.get_yticks(), size = 10)等删除生成的刻度标签。使用bar.tick_params(axis='both', labelsize=10)同时更改x 轴和y 轴的字体大小。问题解决了。 -
成功了,非常感谢@Mr.T!