虚线/曲线图,仅显示直方图中的前10个值

2024-09-27 21:24:31 发布

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

我正在为大学的一门课程创建dash仪表盘。我创建了3个柱状图,但是,有许多独特的值,它们给出了一个很长的x值范围。在我的图中,我只想显示计数最高的10或20个值(前10个值)。有人能帮我吗

import plotly.express as px
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

# Build App
app = JupyterDash(__name__)
app.layout = html.Div([
   html.H1("forensics "),
   dcc.Graph(id='graph'),
   dcc.Graph(id='graph1'),
   dcc.Graph(id='graph2'),
   html.Label([
        "select market",
        dcc.Dropdown(
            id='market', clearable=False,
            value='whitehousemarket', options=[
                {'label': c, 'value': c}
                for c in posts['marketextract'].unique()
            ])
    ]),
])
# Define callback to update graph
@app.callback(
    Output('graph', 'figure'),
    Output('graph1', 'figure'),
    Output('graph2', 'figure'),
    [Input("market", "value")]
)
def update_figure(market):
    fig=px.histogram(x=posts['datetime'].loc[posts['marketextract']==market])
    fig1=px.histogram(x=posts['username'].loc[posts['marketextract']==market])
    fig2=px.histogram(x=posts['drugs'].loc[posts['marketextract']==market])
    return [fig, fig1, fig2]



# Run app and display result inline in the notebook
app.run_server(mode='inline')

enter image description here


Tags: importidappoutputhtmlasmarketgraph
1条回答
网友
1楼 · 发布于 2024-09-27 21:24:31

据我所知,px.histogram()没有一种方法可以排除某些观察到的垃圾箱。但是根据你的数据的查找EME>(请考虑共享一个proper sample),你在这里所做的只是显示一些用户名的不同计数。您可以通过df.groupby()px.histogram的组合轻松实现这一点。或者px.bar()或者go.Bar()对于这件事,但是我们将坚持px.histogram,因为这是您正在寻求帮助的内容。无论如何,使用从px.gapminder随机选择的国家名称,您可以使用:

dfg = df.groupby(['name']).size().to_frame().sort_values([0], ascending = False).head(10).reset_index()
fig = px.histogram(dfg, x='name', y = 'count')

并获得:

enter image description here

如果您删除.head(10),您将得到以下结果:

enter image description here

我希望这就是你想要的功能。不要被漫长的df.groupby(['name']).size().to_frame().sort_values([0], ascending = False).reset_index()吓倒。我不是专家,所以你很可能找到一种更有效的方法。但它确实起到了作用。以下是完整的代码和一些示例数据:

# imports
import pandas as pd
import plotly.express as px
import random

# data sample
gapminder = list(set(px.data.gapminder()['country']))[1:20]
names = random.choices(gapminder, k=100)

# data munging
df = pd.DataFrame({'name':names})
dfg = df.groupby(['name']).size().to_frame().sort_values([0], ascending = False).reset_index()
dfg.columns = ['name', 'count']

# plotly
fig = px.histogram(dfg, x='name', y = 'count')
fig.layout.yaxis.title.text = 'count'
fig.show()

相关问题 更多 >

    热门问题