【问题标题】:Using Altair and 'mark_point' to highlight area in a faceted graph使用 Altair 和 \'mark_point\' 突出显示分面图中的区域
【发布时间】:2023-02-25 05:36:49
【问题描述】:

我正在尝试使用“mark_point”来突出显示多面图中的一个区域,使用 Altair。因为图表是多面的,所以我需要使用相同的数据集来绘制点和突出显示的区域。但是,每个面板的点数不同。据我所知,波段(突出显示的区域)将根据数据集中的点数进行叠加。这当然会影响不透明度,as seen here。 下图显示了我的意思:

有没有办法让不透明度值通过每个面中的点数归一化?也许单独绘制每个区域,并为每个区域确定不同的不透明度值?如果没有,那么我可以在突出显示的区域和点之间绘制网格吗?也许通过绘制多条垂直线和水平线来“重建”网格?

生成上图的代码如下:

import altair as alt
import numpy as np
from vega_datasets import data
import matplotlib.pyplot as plt

source = data.cars()

# adapting data
brand = list()
for i in source['Name']:
    brand.append(i.split(' ')[0])
source['Brand'] = brand

weight = list(set(source['Weight_in_lbs']))
weightArray = np.array_split(weight, 2)
weightClassification = list()
for weight_in_lbs in source['Weight_in_lbs']:
    if weight_in_lbs in weightArray[0]:
        weightClassification.append('light')
    if weight_in_lbs in weightArray[1]:
        weightClassification.append('heavy')
source['weight_classification'] = weightClassification

# remove empty columns
source = source.dropna(subset=['Horsepower', 'Brand', 'Origin', 'weight_classification'])

# define colors and shapes for weight_classification
colors = {"light": "green", "heavy": "steelblue"}
shapes = {"light": "circle", "heavy": "square"}

# define chart
chart = alt.Chart(source).mark_point().encode(
    x=alt.X("Brand:N", title=None, axis=alt.Axis(labelAngle=-90), scale=alt.Scale(padding=1)),
    y=alt.Y("Horsepower:Q", axis=alt.Axis(title='Horsepower', titleFontSize=17)),
    color=alt.Color("weight_classification:N", scale=alt.Scale(domain=list(colors.keys()), range=list(colors.values()))),
    shape=alt.Shape("weight_classification:N", scale=alt.Scale(domain=list(shapes.keys()), range=list(shapes.values()))),
    tooltip=['Name', 'Origin', 'Horsepower', 'Miles_per_Gallon']
)

# plot yellow band with mark_rect
yellow_band = alt.Chart(source).mark_rect(
    color='red',
    opacity=0.01,
).encode(
    y=alt.datum(100),
    y2=alt.datum(140),
)

# combine the all charts
final_chart = alt.layer(
    yellow_band,
    chart
).properties(
    width=alt.Step(25),
    height=350
).facet(
    'Origin:N',
).resolve_scale(
    x='independent'
).configure_axis(
    grid=True
)


final_chart.save('AltairCar.html')

【问题讨论】:

    标签: python graph altair


    【解决方案1】:

    如果 x 轴是定量的,您可以使用 mark_area 而不是 mark_rect like in this example,但是当轴是标称的时,似乎没有一种简单的方法可以做到这一点......

    这里的一种解决方法是选择较浅的颜色并使用完全不透明,以便堆叠和未堆叠的矩形之间没有区别,例如color='#f19f9f'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-19
      • 2012-08-21
      • 1970-01-01
      • 1970-01-01
      • 2013-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多