python - 将数据框设置为系列或显示第 n 个标签
问题描述
每当我将数据集绘制成条形图时,x 轴标签都会被标签超载。如何从数据框中更改 x 轴的数据类型,或者如何显示每第 n 个标签?
这是我的代码:
# Import statements for the packages to be used.
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
# Loading the data and having a look at the first few lines
df = pd.read_csv('tmdb-movies.csv')
df.head()
# Replace 0 with NaN (Not a Number)
df['budget'].replace(0, np.NAN, inplace=True)
df['runtime'].replace(0, np.NAN, inplace=True)
# Drop all rows with null values (NaN)
df.dropna(axis=0, inplace=True)
# Drop all columns not required for investigation
df = df.drop(['id', 'imdb_id', 'revenue', 'cast', 'homepage', 'director', 'tagline',
'keywords', 'overview', 'genres', 'production_companies', 'vote_count', 'vote_average',
'release_date', 'budget_adj', 'revenue_adj'], axis=1)
budget_grp = df.groupby(['budget'])
budget_grp['popularity'].agg(['median', 'mean'])
# Setting mean popularity to variable budget_pop.
budget_pop = budget_grp['popularity'].mean()
# Bar plot with x as budget and y as average popularity.
budget_pop.plot(kind='bar' ,x='budget', y='popularity', figsize=(20,10), xlabel='Budget in
Dollars', ylabel='Average Popularity', rot=0, legend=True)
我试过 enumerate 但不知道该放在哪里。我还尝试创建一个函数来查找 nth 并且我尝试将我的数据框更改为整数,但它们总是出错。
解决方案
您可以使用自定义 xticks:
df = pd.DataFrame(data={'x':np.arange(1,1001,1), 'y':np.random.randint(1,1000,1000)})
ax = df.plot(kind='bar' ,x='x', y='y', figsize=(20,10))
min_value_in_x = 1
max_value_in_x = 1000
x_ticks = np.arange(min_value_in_x, max_value_in_x, 100)
ax.set(xticks=x_ticks, xticklabels=x_ticks)
plt.show()
推荐阅读
- c - 将 sizeof() 应用于 const char *array[] 中的元素
- html - 网格区域 css 无法在 chrome 上正确工作
- r - 尝试使用收到此错误消息的标签创建因子变量:unique.default(x, nmax = nmax) 中的错误:unique() 仅适用于向量
- html - 如何使用百分比 (%) 创建纵横比为 1:1 的完美正方形
- python - 如何使用 CBC 解密密文,其中密文与 IV 和密钥一起给出
- python - 尝试“pip install reportlab==3.0”,我得到一个包含标头的疯狂长错误
- java - (JavaFX) 我的主菜单上有 2 个类似的 TableView,如果我先搜索它,一个实际上并没有删除某些东西
- javascript - Firestore“get”函数多次执行
- python - 为什么每当我尝试运行 VS code python 终端时都会出现语法错误?
- javascript - 当动态创建元素及其类名(例如document.createElement)时,如何将div放入文档中?