[英]Using separate scales for each group in a grouped and stacked barplots in Altair
I'd like to use separate scales for each group in a grouped and stacked barplot using Altair in Python.我想在 Python 中使用 Altair 为分组和堆叠条形图中的每个组使用单独的比例。
So for example instead of the following因此,例如,而不是以下
I'd like something similar to the following.我想要类似下面的东西。 In this (Gimp-)edited picture I have the same scale for all the 4 groups A,B,C and D. But In my actual data, the orders of magnitude are different from a group to another.在这张(Gimp-)编辑的图片中,我对所有 4 组 A、B、C 和 D 具有相同的比例。但在我的实际数据中,数量级因一组而异。 So each Group should have a different scale.所以每个组应该有不同的规模。 Any ideas on how to do that?关于如何做到这一点的任何想法?
Here is an Minimum Example from HERE这是来自HERE的最小示例
import pandas as pd
import numpy as np
import altair as alt
df1=pd.DataFrame(10*np.random.rand(4,3),index=["A","B","C","D"],columns=["I","J","K"])
df2=pd.DataFrame(10*np.random.rand(4,3),index=["A","B","C","D"],columns=["I","J","K"])
df3=pd.DataFrame(10*np.random.rand(4,3),index=["A","B","C","D"],columns=["I","J","K"])
def prep_df(df, name):
df = df.stack().reset_index()
df.columns = ['c1', 'c2', 'values']
df['DF'] = name
return df
df1 = prep_df(df1, 'DF1')
df2 = prep_df(df2, 'DF2')
df3 = prep_df(df3, 'DF3')
df = pd.concat([df1, df2, df3])
chart = alt.Chart(df).mark_bar().encode(
x=alt.X('c2:N', title=None),
y=alt.Y('sum(values):Q', axis=alt.Axis(grid=False, title=None)),
column=alt.Column('c1:N', title=None),
color=alt.Color('DF:N', scale=alt.Scale(range=['#96ceb4', '#ffcc5c','#ff6f69']))
).configure_view(
strokeOpacity=0
)
chart.save("Power.svg")
You can have independent axes for the charts by adding您可以通过添加图表来拥有独立的轴
resolve_scale(y='independent')
Note that, by itself, this lets the y-domain limits for each facet adjust to the subset of the data within each facet;请注意,这本身可以让每个方面的 y 域限制调整为每个方面内的数据子集; you can make them match by explicitly specifying domain limits.您可以通过明确指定域限制来使它们匹配。
Put together, it looks like this:放在一起,它看起来像这样:
alt.Chart(df).mark_bar().encode(
x=alt.X('c2:N', title=None),
y=alt.Y('sum(values):Q', axis=alt.Axis(grid=False, title=None), scale=alt.Scale(domain=[0, 25])),
column=alt.Column('c1:N', title=None),
color=alt.Color('DF:N', scale=alt.Scale(range=['#96ceb4', '#ffcc5c','#ff6f69']))
).configure_view(
strokeOpacity=0
).resolve_scale(
y='independent'
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.