'How remove axis, connect dots with a line, and add fillOpacity to the legend in Altair?

I have seen various responses in threads here and on Github which mention that some manual alterations can be made to an Altair graph by using CSS, but I am unsure how one would go about doing this. Specifically, I have the following code and graph:

alt.Chart(data).mark_circle(opacity=1, stroke='#4c78a8').encode(
    x='Paragraph:N',
    y=alt.Y('Section:N', sort=list(OrderedDict.fromkeys(data['Section']))),
    size='algo_score_normalized:Q',
    fillOpacity=alt.FillOpacity(
        'fill:Q',
        scale=None
    )
).properties(
    width=600,
    height=400
)

enter image description here

I would like to make the following changes:

  1. Get rid of the x-axis completely so there is no label or line
  2. Change the legend to have different values and for the filling of the legend circles to match the filling of the circles in the graph (i.e. below 0.4 is not filled).
  3. I'd like to draw horizontal lines connecting all the circles in a given row (kind of like a network graph).

Can these be done either natively or using CSS?



Solution 1:[1]

You can disable the axis via axis=None and use mark_rule to connect the dots with a line. However, VegaLite does not support fillOpacity in the legend so you would have to use a workaround, e.g. creating a point and a circle mark as in my example below.

import altair as alt
from vega_datasets import data


cars = data.cars().sample(10, random_state=239)
fills = alt.Chart(cars.query('Cylinders > 4')).mark_circle(size=200, opacity=1).encode(
    x=alt.X('Miles_per_Gallon', axis=None),
    y='Cylinders:O',
    color='Cylinders:O'
)

fills_rule = alt.Chart(cars.query('Cylinders > 4')).mark_rule(stroke='#5ba3cf').encode(
    x=alt.value(190),
    y='Cylinders:O'
)


strokes = alt.Chart(cars.query('Cylinders == 4')).mark_point(size=200, opacity=1).encode(
    x=alt.X('Miles_per_Gallon', axis=None),
    y='Cylinders:O',
    color=alt.Color('Cylinders:O', title='')
)

strokes_rule = alt.Chart(cars.query('Cylinders == 4')).mark_rule(stroke='#5ba3cf').encode(
    x=alt.value(385),
    y='Cylinders:O'
)

(fills_rule
 + fills
 + strokes_rule
 + strokes
).resolve_scale(color='independent')

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 joelostblom