【问题标题】:Creating column based subplots创建基于列的子图
【发布时间】:2020-10-07 04:00:09
【问题描述】:

所以我有以下问题,需要使用提供的数据制作 3 个子图。我遇到的问题是我需要从“genre_1”列中为三个子图中的每一个选择一个特定的流派。我无法弄清楚如何选择特定数据。我已经提供了一个输出应该是什么样子的示例。

 from plotly.subplots import make_subplots
    import plotly.graph_objects as go

    movies = {'title_year': {0: 2016, 1: 2016, 2: 2016, 3: 2016, 4:2016},'Title': {0: 'La La Land', 1: 'Zootopia',2: 'Lion',3: 'Arrival', 4: 'Manchester by the Sea'},'Runtime': {0: 128, 1: 108, 2: 118, 3: 116, 4: 137},'IMDb_rating': {0: 8.2, 1: 8.1, 2: 8.1, 3: 8.0, 4: 7.9},'genre_1': {0: 'Action',1: 'Animation',2: 'Biography',3: 'Drama',4: 'Drama'}}

    # Create a subplot, using column, 'genre_1' for three genres - 'Action','Drama','Biography' 

    sub_fig = make_subplots(rows=1, cols=3)

    fig.add_trace(go.Scatter(x='Runtime', y='IMDb_rating',row=1, col=1)
    fig.add_trace(go.Scatter(x='Runtime', y='IMDb_rating',row=1, col=2)
    fig.add_trace(go.Scatter(x='Runtime', y='IMDb_rating',row=1, col=3)

Output

【问题讨论】:

  • 请提供您的数据样本(不是图片)
  • 编辑您的问题并将您的数据框粘贴到那里(请参阅here
  • @DavideBrex 我已经添加了数据

标签: python pandas plotly subplot


【解决方案1】:

这应该可行:

list_genre = list(df.genre_1.unique())
sub_fig = make_subplots(rows=1, cols=len(list_genre), subplot_titles= list_genre)

for i,genre in enumerate(list_genre):
    sub_fig.add_trace(go.Scatter(x = df[df.genre_1==genre]["Runtime"],
                             y=df[df.genre_1==genre]["IMDb_rating"]),row=1, col=i+1)


sub_fig.show()

输出:

编辑: 这是您需要的代码:

genres_to_plot = ['Action','Drama','Biography']
subset_movies = movies[movies.genre_1.isin(genres_to_plot)].reset_index(drop=True)

fig = px.scatter(subset_movies, x = "Runtime", y = "IMDb_rating", color = "genre_1", facet_col="genre_1", height = 480, width = 850)
fig.show()

输出图:

您只需将参数facet_col 添加到px.scatter。如果您想要气泡图,请添加 size="actor_1_facebook_likes"

【讨论】:

  • 我正在尝试仅为genre_1 == 'Action'创建子图,我收到以下代码的EOF解析错误,无法确定我在哪里犯了错误 sub_fig.add_trace( go.Scatter(x=movies[movies['genre_1'] == 'Action']['Runtime'], y=movies[movies['genre_1'] == 'Action']['IMDb_rating'],row= 1, cols=1)
  • 您在 row=1 之前忘记了一个圆括号:sub_fig.add_trace(go.Scatter(x=movies[movies['genre_1'] == 'Action']['Runtime'], y=movies[movies['genre_1'] == 'Action']['IMDb_rating']),row=1, cols=1)
  • sub_fig.add_trace(go.Scatter(x=movies[movies['genre_1'] == 'Action']['Runtime'], y=movies[movies['genre_1'] == 'Action']['IMDb_rating']),row=1, col=1)
  • sub_fig.add_trace(go.Scatter(x=movies[movies['genre_1'] == 'Action']['Runtime'], y=movies[movies['genre_1'] == 'Action']['IMDb_rating']),row=1, col=1) 上面的代码不会给我一个错误,但是我的散点图看起来像之字形线,所有的数据点都是连接的,知道为什么吗?
  • 也许你需要在绘图前根据 RunTime 列对行进行排序,但是没有看到输出很难帮助你!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多