首页 > 解决方案 > 将数据框设置为系列或显示第 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 并且我尝试将我的数据框更改为整数,但它们总是出错。

在此处输入图像描述

后续回答如下: 在此处输入图像描述

在此处输入图像描述

标签: pythonpandasnumpymatlab

解决方案


您可以使用自定义 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()

推荐阅读