如何在绘图分组条形图中提取适当的数据?

2024-05-20 01:07:14 发布

您现在位置:Python中文网/ 问答频道 /正文

嗯,我试图在Plotly中绘制一个条形图,其中我需要在分组条形图中显示3年的数据,尽管该图表在图表中显示数据,但没有正确显示数据。所有的条形图在图形中都是相等的,如下所示: enter image description here

以下是我的绘图代码:

data=[go.Bar(x=nasdaq['Sector'],y=recent_ipos['IPO Year'],textangle=-45,name='2015'),
go.Bar(x=nasdaq['Sector'],y=recent_ipos['IPO Year'],textangle=-45,name='2016'),
go.Bar(x=nasdaq['Sector'],y=recent_ipos['IPO Year'],textangle=-45,name='2017')
]

layout=go.Layout(title="NASDAQ Market Capitalization IPO yEAR (million USD)",barmode='group')
fig=go.Figure(data=data,layout=layout)
fig.show(renderer="colab")

以下是我3年来提取数据的代码:

recent_ipos = nasdaq[nasdaq['IPO Year'] > 2014]
recent_ipos['IPO Year'] = recent_ipos['IPO Year'].astype(int)

我试图在这里使用数组提取2015年的数据,但我没有找到从数组中提取元素的合适方法

ipo2015=np.array(recent_ipos['IPO Year'])
ipo2015

我不确定这是否是提取特定年份数据的正确方法?? 我想知道的是:

如何使用Plotly在图形中正确提取年份数据

我应该做哪些更改来解决图表中的这种不一致性

在所有三组条中,我应该在Y=中加什么

如何动态提取年份而不是手动提取

希望在StackOverflow上得到这个令人惊叹的社区的帮助。 提前感谢


Tags: 数据namegodata图表baryear条形图
1条回答
网友
1楼 · 发布于 2024-05-20 01:07:14

我编写代码时假设问题所基于的数据是数据帧格式。数据取自plotly。query()也可以用作使用@的变量,如代码所示

import plotly.graph_objects as go
import plotly.express as px

# yyyy = [1992,1997,2002]
df = px.data.gapminder()
continent = df['continent'].unique().tolist()
yyyy = df['year'].unique().tolist()[-3:] # update
data = []
for y in yyyy:
    # tmp_df = df.query('year == @y')
    tmp_df = df[df['year'] == y].groupby('continent')['pop'].sum()
    data.append(go.Bar(x=tmp_df.index, y=tmp_df, name=y))
    
# Change the bar mode
fig = go.Figure(data)
fig.update_layout(barmode='group')
fig.show()

enter image description here

相关问题 更多 >