本文介绍了如何旋转seaborn barplot x轴刻度标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正试图获得一个绘制图,以将其X标签旋转45度,以使其可读(原样,存在重叠).
len(genero)
是 7,len(filmes_por_genero)
是 20
我正在使用MovieLens数据集,并制作了一个图表,计算每个流派中电影的数量.到目前为止,这是我的代码:
导入 seaborn 为 sns导入matplotlib.pyplot作为pltsns.set_style(whitegrid")filmes_por_genero = filmes[generos"].str.get_dummies('|').sum().sort_values(ascending=False)基因 = filmes_com_media.index图表= plt.figure(figsize =(16,8))sns.barplot(x=genero,y = filmes_por_genero.values,调色板=sns.color_palette(BuGn_r", n_colors=len(filmes_por_genero) + 4))chart.set_xticklabels(chart.get_xticklabels(),旋转= 45,水平对齐='右')
这是完整的错误:
get_grouper中的 /usr/local/lib/python3.6/dist-packages/pandas/core/groupby/grouper.py(obj,键,轴,级别,排序,观察到的,变异的,验证的)第623话624)->625如果不是isinstance(gpr,分组)第 626 章627)__init__中的/usr/local/lib/python3.6/dist-packages/pandas/core/groupby/grouper.py(自身,索引,石斑鱼,obj,名称,级别,排序,观察到的in_axis)第254话255 self.level = level->256 self.grouper = _convert_grouper(索引,石斑鱼)第257话258 self.index = 索引_convert_grouper(axis,grouper)中的/usr/local/lib/python3.6/dist-packages/pandas/core/groupby/grouper.py第653回第654话->655引发ValueError(石斑鱼和轴的长度必须相同")656回石斑鱼657其他:ValueError:石斑鱼和轴的长度必须相同
解决方案
- 数据来自
情节:
I'm trying to get a barplot to rotate it's X Labels in 45° to make them readable (as is, there's overlap).
len(genero)
is 7, andlen(filmes_por_genero)
is 20I'm using a MovieLens dataset and making a graph counting the number of movies in each individual genre. Here's my code as of now:
import seaborn as sns import matplotlib.pyplot as plt sns.set_style("whitegrid") filmes_por_genero = filmes["generos"].str.get_dummies('|').sum().sort_values(ascending=False) genero = filmes_com_media.index chart = plt.figure(figsize=(16,8)) sns.barplot(x=genero, y=filmes_por_genero.values, palette=sns.color_palette("BuGn_r", n_colors=len(filmes_por_genero) + 4) ) chart.set_xticklabels( chart.get_xticklabels(), rotation=45, horizontalalignment='right' )
Here's the full error:
/usr/local/lib/python3.6/dist-packages/pandas/core/groupby/grouper.py in get_grouper(obj, key, axis, level, sort, observed, mutated, validate) 623 in_axis=in_axis, 624 ) --> 625 if not isinstance(gpr, Grouping) 626 else gpr 627 ) /usr/local/lib/python3.6/dist-packages/pandas/core/groupby/grouper.py in __init__(self, index, grouper, obj, name, level, sort, observed, in_axis) 254 self.name = name 255 self.level = level --> 256 self.grouper = _convert_grouper(index, grouper) 257 self.all_grouper = None 258 self.index = index /usr/local/lib/python3.6/dist-packages/pandas/core/groupby/grouper.py in _convert_grouper(axis, grouper) 653 elif isinstance(grouper, (list, Series, Index, np.ndarray)): 654 if len(grouper) != len(axis): --> 655 raise ValueError("Grouper and axis must be same length") 656 return grouper 657 else: ValueError: Grouper and axis must be same length
解决方案- Data from MovieLens 25M Dataset at MovieLens
import pandas as pd import mathplotlib.pyplot as plt import seaborn as sns sns.set_style("whitegrid") # data df = pd.read_csv('ml-25m/movies.csv') print(df.head()) movieId title genres 0 1 Toy Story (1995) Adventure|Animation|Children|Comedy|Fantasy 1 2 Jumanji (1995) Adventure|Children|Fantasy 2 3 Grumpier Old Men (1995) Comedy|Romance 3 4 Waiting to Exhale (1995) Comedy|Drama|Romance 4 5 Father of the Bride Part II (1995) Comedy # clean genres df['genres'] = df['genres'].str.split('|') df = df.explode('genres').reset_index(drop=True) print(df.head()) movieId title genres 0 1 Toy Story (1995) Adventure 1 1 Toy Story (1995) Animation 2 1 Toy Story (1995) Children 3 1 Toy Story (1995) Comedy 4 1 Toy Story (1995) Fantasy
Genres Counts
gc = df.genres.value_counts().to_frame() print(genre_count) genres Drama 25606 Comedy 16870 Thriller 8654 Romance 7719 Action 7348 Horror 5989 Documentary 5605 Crime 5319 (no genres listed) 5062 Adventure 4145 Sci-Fi 3595 Children 2935 Animation 2929 Mystery 2925 Fantasy 2731 War 1874 Western 1399 Musical 1054 Film-Noir 353 IMAX 195
Plot:
sns.barplot
With
ax
fig, ax = plt.subplots(figsize=(12, 6)) sns.barplot(x=gc.index, y=gc.genres, palette=sns.color_palette("BuGn_r", n_colors=len(genre_count) + 4), ax=ax) ax.set_xticklabels(ax.get_xticklabels(), rotation=45, horizontalalignment='right') plt.show()
Without
ax
plt.figure(figsize=(12, 6)) chart = sns.barplot(x=gc.index, y=gc.genres, palette=sns.color_palette("BuGn_r", n_colors=len(genre_count))) chart.set_xticklabels(chart.get_xticklabels(), rotation=45, horizontalalignment='right') plt.show()
Plot:
sns.countplot
- Use
sns.countplot
to skip using.value_counts()
if the plot order doesn't matter. - To order the
countplot
,order=df.genres.value_counts().index
must be used, socountplot
doesn't really save you from needing.value_counts()
, if a descending order is desired.
fig, ax = plt.subplots(figsize=(12, 6)) sns.countplot(data=df, x='genres', ax=ax) ax.set_xticklabels(ax.get_xticklabels(), rotation=45, horizontalalignment='right') plt.show()
这篇关于如何旋转seaborn barplot x轴刻度标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!