我怎样才能像这个牛郎星一样并排创建一个条形图呢?

2024-04-23 18:00:16 发布

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

Image of What I want to create

我在图表的左侧(前三名),尝试创建一个“bars2”和“text2”字段,但没有成功,并将其添加到原始的“ranked_movies”字段中,但这太混乱了。有没有一种方法可以移动和压缩,或者添加一整套其他的条形图

tuples = list(zip([names[ep] for ep in episodes],topthird,middlethird))
binranking_per_df = pd.DataFrame(tuples, columns = ['Name', 'Top Third','Middle Third'])
#ranking_per_df


bars = alt.Chart(binranking_per_df).mark_bar(size=20).encode(
    x=alt.X(
        'Top Third',
        axis=None),
    y=alt.Y(
        'Name:N',
         axis=alt.Axis(tickCount=5, title=''),
         sort=names_l
    )
)

bars2 = alt.Chart(binranking_per_df).mark_bar(size=20).encode(
    x=alt.X(
        'Middle Third',
        axis=None),
    y=alt.Y(
        'Name:N',
         axis=alt.Axis(tickCount=5, title=''),
         sort=names_l
    )
)

text = bars.mark_text(
    align='left',
    baseline='middle',
    dx=3  
).encode(
    text=alt.Text('Top Third:Q',format='.0%')
)

text2 = bars.mark_text(
    align='left',
    baseline='middle',
    dx=3  
).encode(
    text=alt.Text('Middle Third:Q',format='.0%')
)

ranked_movies = (text + bars).configure_mark(
    color='#008fd5'
).configure_view(
    strokeWidth=0
).configure_scale(
    bandPaddingInner=0.2
).properties(
    width=500,
    height=180
).properties(
    title="Whats the Best 'Star Wars' Movie?"
)

Tags: textnamemiddledfnamestitletopalt
1条回答
网友
1楼 · 发布于 2024-04-23 18:00:16

这个问题(关于同一个图表)以前已经回答过here,但不幸的是,这个问题被用户删除了

我的回答是:


Altair gallery提供了一些平面条形图的示例(例如this one)。对于您心目中的图表,您可以通过facetingaLayer Chart继续操作,其中包含一个条形图和一个文本层。例如:

import altair as alt
import numpy as np
import pandas as pd

titles = ['The Phantom Menace', 'Attack of the Clones', 'Revenge of the Sith',
          'A New Hope', 'The Empire Strikes Back', 'Return of the Jedi']
categories = ['Top third', 'Middle third', 'Bottom third']
percentages = [
    [0.16, 0.14, 0.13, 0.50, 0.64, 0.43],
    [0.37, 0.29, 0.40, 0.31, 0.22, 0.41],
    [0.46, 0.57, 0.47, 0.19, 0.14, 0.17]
]
titles, categories, percentages = map(
    np.ravel, np.broadcast_arrays(
        titles, np.array(categories)[:, None], percentages))
df = pd.DataFrame({
    'titles': titles,
    'categories': categories,
    'percentages': percentages,
})

base = alt.Chart(df).encode(
    x=alt.X('percentages:Q', axis=None),
    y=alt.Y('titles:N', title=None, sort=titles),
).properties(
    width=70
)

bars = base.mark_bar().encode(
    color=alt.Color('categories:N', legend=None)
)
text = base.mark_text(dx=15).encode(
    text=alt.Text('percentages:Q', format=".0%")
)

(bars + text).facet(
    column=alt.Column('categories:N', title=None, sort=categories)
).configure_view(
    stroke='transparent'
)

enter image description here

相关问题 更多 >