在破折号的条形图中删除高度为0的条

时间:2019-01-29 07:42:13

标签: python-3.x bar-chart plotly plotly-dash

我试图用虚线制作一个组条形图,我在x轴上绘制主题代码,因此它们不是连续的数字,而对于缺少的主题代码,我得到的是空条,因此有什么方法可以删除这些空格或看不见的条。 This is the bar graph I am getting. 这是我的代码。

df = pd.read_csv('sampledata.csv')
a=df['SiteCode'].loc[df['SubjectStatus']=='In Progress'].value_counts()
a.index=a.index.astype(str)
b=df['SiteCode'].loc[df['SubjectStatus']=='Withdrawn'].value_counts()
b.index=b.index.astype(str)
x1=a.index
x2=b.index
trace1=go.Bar(
    x=x1,
    y=a.values,
    name='In Progress',
)
trace2=go.Bar(
    x=x2,
    y=b.values,
    name='Withdrawn',
)
app = dash.Dash()
app.layout = html.Div(
    dcc.Graph(id='graph',
        figure=go.Figure(data=[trace1,trace2],layout=go.Layout(barmode='group')))

if __name__=='__main__':
    app.run_server()

预先感谢

PS:我是破折号和python的菜鸟,所以对我轻松一点。

1 个答案:

答案 0 :(得分:1)

您应该尝试设置barmode='stack',因为如果您的一条迹线具有空值,barmode='group'会添加空白。

import dash
from dash.dependencies import Output, Input
import dash_core_components as dcc
import dash_html_components as html
import plotly
import plotly.graph_objs as go
import pandas as pd

app = dash.Dash(__name__)

df = pd.DataFrame({'x': [100, 100, 105, 110, 110, 115, 120, 125],
                   'y': [1, 2, 1, 1, 2, 2, 1, 1]})

colors = {
    'background': '#111111',
    'background2': '#FF0',
    'text': '#7FDBFF'
}
df1 = df.loc[df["y"] == 1]
df2 = df.loc[df["y"] == 2]
trace1 = go.Bar(
                x=df1["x"],
                y=df1["y"],
                name='In Progress',
)
trace2 = go.Bar(
                x=df2["x"],
                y=df2["y"],
                name='Withdrawn',
)

app.layout = html.Div(children=[
        html.Div([
            html.H5('ANNx'),
            dcc.Graph(
                id='cx1',
                figure=go.Figure(data=[trace1, trace2],
                                 layout=go.Layout(barmode='group')))],)])


if __name__ == '__main__':
    app.run_server(debug=True)

例如,在此代码中,值为105、115和120的一条迹线为空,并在绘图中创建空间: Bar group

使用另一个barmode解决了此问题:

Bar stacked