【发布时间】: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')
【问题讨论】: