更改具有不同 bin 数量的图表的宽度
Change the width of a chart plot with different number of bins
我有如下图表(代码在最后)
我需要增加它的宽度。
如果我设置alt.Chart(df, width=100, height=90)
,那么条数较少的组的条宽太大,像这样
如果我设置 alt.Chart(df, height=90).mark_bar(size=20)
,那么条会重叠,就像这样
import numpy as np
import pandas as pd
import altair as alt
np.random.seed(0)
model_keys = ['M1', 'M2']
scene_keys = ['S1', 'S2', 'S3']
layer_keys = ['L1', 'L2']
ys = []
models = []
dataset = []
layers = []
scenes = []
for sc in scene_keys:
for m in model_keys:
for l in layer_keys:
if sc == 'S3' and l == 'L1':
continue
for s in range(10):
y = np.random.rand(10) / 10
data_y = list(y)
ys += data_y
scenes += [sc] * len(data_y)
models += [m] * len(data_y)
layers += [l] * len(data_y)
df = pd.DataFrame({'Y': ys,
'Model': models,
'Layer': layers,
'Scenes': scenes})
bars = alt.Chart(df, height=90).mark_bar().encode(
x=alt.X('Scenes:N',
title=None,
axis=alt.Axis(
grid=False,
title=None,
labels=False,
),
),
y=alt.Y('Y:Q',
aggregate='mean',
axis=alt.Axis(
grid=True,
title='Y',
titleFontWeight='normal',
),
),
)
bars = bars.facet(
row=alt.Row('Model:N',
title=None,
),
column=alt.Column('Layer:N',
title=None,
),
spacing={"row": 10, "column": 10},
)
bars = bars.resolve_scale(x='independent')
bars.save('test.html')
您可以通过 step
属性 指定图表宽度,而不是指定条形的宽度(这不影响图表的默认宽度),这将同时调整条形宽度和图表宽度加在一起:
alt.Chart(df, height=90, width={"step": 20}).mark_bar().encode(...
我有如下图表(代码在最后)
我需要增加它的宽度。
如果我设置alt.Chart(df, width=100, height=90)
,那么条数较少的组的条宽太大,像这样
如果我设置 alt.Chart(df, height=90).mark_bar(size=20)
,那么条会重叠,就像这样
import numpy as np
import pandas as pd
import altair as alt
np.random.seed(0)
model_keys = ['M1', 'M2']
scene_keys = ['S1', 'S2', 'S3']
layer_keys = ['L1', 'L2']
ys = []
models = []
dataset = []
layers = []
scenes = []
for sc in scene_keys:
for m in model_keys:
for l in layer_keys:
if sc == 'S3' and l == 'L1':
continue
for s in range(10):
y = np.random.rand(10) / 10
data_y = list(y)
ys += data_y
scenes += [sc] * len(data_y)
models += [m] * len(data_y)
layers += [l] * len(data_y)
df = pd.DataFrame({'Y': ys,
'Model': models,
'Layer': layers,
'Scenes': scenes})
bars = alt.Chart(df, height=90).mark_bar().encode(
x=alt.X('Scenes:N',
title=None,
axis=alt.Axis(
grid=False,
title=None,
labels=False,
),
),
y=alt.Y('Y:Q',
aggregate='mean',
axis=alt.Axis(
grid=True,
title='Y',
titleFontWeight='normal',
),
),
)
bars = bars.facet(
row=alt.Row('Model:N',
title=None,
),
column=alt.Column('Layer:N',
title=None,
),
spacing={"row": 10, "column": 10},
)
bars = bars.resolve_scale(x='independent')
bars.save('test.html')
您可以通过 step
属性 指定图表宽度,而不是指定条形的宽度(这不影响图表的默认宽度),这将同时调整条形宽度和图表宽度加在一起:
alt.Chart(df, height=90, width={"step": 20}).mark_bar().encode(...