Plotly中的Bar Charts

条形图

效果

Bar

代码

1
2
3
4
5
import plotly.express as px
data_canada = px.data.gapminder().query("country == 'Canada'")
fig = px.bar(data_canada, x='year', y='pop')
fig.show()

长格式数据

效果

Format

代码

1
2
3
4
5
6
7
import plotly.express as px

long_df = px.data.medals_long()

fig = px.bar(long_df, x="nation", y="count", color="medal", title="Long-Form Input")
fig.show()

多面子图

效果

Facetted

代码

1
2
3
4
5
6
7
import plotly.express as px
df = px.data.tips()
fig = px.bar(df, x="sex", y="total_bill", color="smoker", barmode="group",
facet_row="time", facet_col="day",
category_orders={"day": ["Thur", "Fri", "Sat", "Sun"],
"time": ["Lunch", "Dinner"]})
fig.show()

其中,barmode="group"防止堆叠,category_orders定义了行列

自定义单个条形颜色

效果

Customizing

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import plotly.graph_objects as go

colors = ['lightslategray',] * 5
colors[1] = 'crimson'

fig = go.Figure(data=[go.Bar(
x=['Feature A', 'Feature B', 'Feature C',
'Feature D', 'Feature E'],
y=[20, 14, 23, 25, 22],
marker_color=colors # marker color can be a single color value or an iterable
)])
fig.update_layout(title_text='Least Used Feature')
fig.show()

自定义宽度

效果

width

代码

1
2
3
4
5
6
7
8
9
10
import plotly.graph_objects as go

fig = go.Figure(data=[go.Bar(
x=[1, 2, 3, 5.5, 10],
y=[10, 8, 6, 4, 2],
width=[0.8, 0.8, 0.8, 3.5, 4] # customize width here
)])

fig.show()

自定义基点

效果

base

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import plotly.graph_objects as go

years = ['2016', '2017', '2018']

fig = go.Figure()
fig.add_trace(go.Bar(x=years, y=[500, 600, 700],
base=[-500, -600, -700],
marker_color='crimson',
name='expenses'))
fig.add_trace(go.Bar(x=years, y=[300, 400, 700],
base=0,
marker_color='lightslategrey',
name='revenue'
))

fig.show()

自定义间距

效果

Gaps

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import plotly.graph_objects as go

years = [1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012]

fig = go.Figure()
fig.add_trace(go.Bar(x=years,
y=[219, 146, 112, 127, 124, 180, 236, 207, 236, 263,
350, 430, 474, 526, 488, 537, 500, 439],
name='Rest of world',
marker_color='rgb(55, 83, 109)'
))
fig.add_trace(go.Bar(x=years,
y=[16, 13, 10, 11, 28, 37, 43, 55, 56, 88, 105, 156, 270,
299, 340, 403, 549, 499],
name='China',
marker_color='rgb(26, 118, 255)'
))

fig.update_layout(
title='US Export of Plastic Scrap',
xaxis_tickfont_size=14,
yaxis=dict(
title='USD (millions)',
titlefont_size=16,
tickfont_size=14,
),
legend=dict(
x=0,
y=1.0,
bgcolor='rgba(255, 255, 255, 0)',
bordercolor='rgba(255, 255, 255, 0)'
),
barmode='group',
bargap=0.15, # gap between bars of adjacent location coordinates.
bargroupgap=0.1 # gap between bars of the same location coordinate.
)
fig.show()

官方文档