matplotlib 如何旋转海运条形图X轴刻度标签

qlvxas9a  于 2022-11-15  发布在  其他
关注(0)|答案(2)|浏览(264)

我试图得到一个条形图旋转它的X标签在45°,使他们可读(因为是,有重叠)。
len(genero)为7,并且len(filmes_por_genero)为20
我使用了MovieLens数据集,并制作了一个统计每种类型电影数量的图表。

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

以下是完整的错误:

/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
xnifntxz

xnifntxz1#

import pandas as pd
import matplotlib.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

类型计数

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

sns.barplot(第一个字母)

第一次

sns.countplot(一个数字)

  • 如果出图顺序无关紧要,请使用sns.countplot来略过使用.value_counts()
  • 要对countplot进行排序,必须使用order=df.genres.value_counts().index,因此,如果需要降序排序,countplot并不能真正保存您对.value_counts()的需求。
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()

mwkjh3gx

mwkjh3gx2#

标签旋转的短代码:

plt.xticks(rotation=45, ha='right')
  • 将标示旋转45度
  • 将标签水平向右对齐以提高可读性
    完整示例

sns.countplot,x轴已排序

import seaborn as sns
import matplotlib.pyplot as plt
df = sns.load_dataset('planets')
sns.countplot(data=df,
              x='method',
              order=df['method'].value_counts().index)
plt.xticks(rotation=45, ha='right');

相关问题