【问题标题】:Prettifying Matplotlib Line Graph美化 Matplotlib 折线图
【发布时间】:2019-01-19 16:50:34
【问题描述】:

我想要实现的是一个流派的折线图以及它们在整个历史中的平均得分。 X 轴 = 年,y 轴 = 分数。

genre_list 是流派类型的数组。

for genre in genre_list:
    random_color = [np.random.random_sample(), np.random.random_sample(), np.random.random_sample()]
    plt.plot('release_year', 'vote_average', 
             data=genre_df, marker='', 
             markerfacecolor=random_color, 
             markersize=1, 
             color=random_color, 
             linewidth=1, 
             label = genre)

plt.legend()
plt.figure(figsize=(5,5))

虽然我得到的结果很丑。

问题 1)我尝试设置图形大小,但它似乎保持相同的比例。我该如何配置?

问题2)如何设置线条颜色以匹配图例?

问题 3) 如何配置 x 和 y 轴以使其更精确? (可能与 #1 相同的问题)

感谢您提供任何形式的意见,谢谢。

【问题讨论】:

  • (1) 您需要在 绘图之前创建具有预想尺寸的图形。 (2) 目前,您正在多次绘制相同的数据。我似乎想在每个循环步骤中使用不同的数据。 (3) 参见例如here.
  • 请说明genre_list是如何生成的。
  • @Parfait genre_list = np.unique(genre_df['genres'].tolist()) print(genre_list) 返回:['Action' 'Adventure' 'Animation' 'Comedy' 'Crime' 'Documentary' 'Drama' 'Family' 'Fantasy' 'Foreign' 'History' 'Horror' 'Music' 'Mystery' 'Romance' 'Science Fiction' 'TV Movie' 'Thriller' 'War' 'Western']

标签: python pandas dataframe matplotlib graph


【解决方案1】:

考虑 groupbygenre 拆分数据帧,然后循环遍历子集以获取绘图线。正如上面的@ImportanceOfBeingErnest 引用,使用这个SO answer 每年间隔x 轴(根据需要旋转刻度):

import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
...

fig, ax = plt.subplots(figsize=(12,5))

for genre, sub_df in genre_df.groupby(['genres']):
    random_color = [np.random.random_sample() for _ in range(3)]

    plt.plot('release_year', 'vote_average', 
             data = sub_df, marker = '', 
             markerfacecolor = random_color, 
             markersize = 1, 
             color = random_color, 
             linewidth = 1, 
             label = genre)

loc = plticker.MultipleLocator(base=1.0)
ax.xaxis.set_major_locator(loc)
plt.xticks(rotation=45)

plt.legend()
plt.show()
plt.clf()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 2017-07-16
    • 2021-09-06
    • 2022-01-26
    相关资源
    最近更新 更多