It seems like you can't add a subtitle yet to a title on a graph made using the Altair Python library.
I love Altair, but according to the threads I've found Altair doesn't have a subtitling capability for a graph. Has anyone figured out how to add a subtitle? I thought of line breaks, but it looks like support for that is still getting added to Vega/Vega-lite, which is what Altair is based on.
Here's everything that I think can be found on this narrow issue...
Here is the Altair team saying it's a Vega issue:
https://github.com/altair-viz/altair/issues/987
Here is the Vega team saying it's not fixed yet (I think):
https://github.com/vega/vega-lite/issues/4055
If you can find any way to add a subtitle to either a title or an axis label, that would be huge!!
One of the best things about about the altair/vega-lite/vega ecosystem is how active it is. Since the last posting there have been a number of developments across the tool chain (this pr in particular) that have addressed exactly this issue!!
That change also adds multi-line support for titles, in addition to multiline subtitles. Example code snippet:
import altair as alt
from vega_datasets import data
chart = alt.Chart(data.cars.url).mark_point().encode(
x='Horsepower:Q',
y='Miles_per_Gallon:Q',
).properties(
title={
"text": ["First line of title", "Second line of title"],
"subtitle": ["Cool first line of subtitle", "Even cooler second line wow dang"],
"color": "red",
"subtitleColor": "green"
}
)
chart
Which yields:
Altair does not support subtitles, because Vega-Lite, the library that renders Altair charts, does not support subtitles.
That said, you can hack together something like a subtitle using chart concatenation, if you wish. For example:
import altair as alt
from vega_datasets import data
cars = data.cars()
title = alt.Chart(
{"values": [{"text": "The Title"}]}
).mark_text(size=20).encode(
text="text:N"
)
subtitle = alt.Chart(
{"values": [{"text": "Subtitle"}]}
).mark_text(size=14).encode(
text="text:N"
)
chart = alt.Chart(cars).mark_point().encode(
x='Horsepower',
y='Miles_per_Gallon',
color='Origin'
)
alt.vconcat(
title,
subtitle,
chart
).configure_view(
stroke=None
).configure_concat(
spacing=1
)
You could also use alt.TitleParams
instead of creating the dictionary manually and set the title in Chart
directly instead of using the .properties
method:
import altair as alt
from vega_datasets import data
plot_title = alt.TitleParams("Main figure title", subtitle=["First line", "Second line"])
alt.Chart(data.cars.url, title=plot_title).mark_point().encode(
x='Horsepower:Q',
y='Miles_per_Gallon:Q')
If you print the plot_title
variable, you will see that it contains a dictionary similar to that used in mcnutt's earlier answer.
TitleParams({
subtitle: ['First line', 'Second line'],
text: 'Main figure title'
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With