question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Is it possible to use custom strings for legend labels?

See original GitHub issue

Is it possible to pass a custom list of strings for the legend labels? In a chart, I want to show missing values as a part of the total so I use a stacked barchart where the segments/pieces(?) come from two columns: Missing and Difference , combined together they add up to the total. The legend shows the two variables as Missing and Difference and I would like to be able to change Difference -> Total somehow.

df = pd.DataFrame(
  {'Year': [2014, 2015, 2016, 2017, 2018, 2019],
   'Total': [376, 1198, 1871, 4386, 4920, 2417],
   'Missing': [299, 758, 1063, 233, 32, 11],
   'Difference': [77, 440, 808, 4153, 4888, 2406]}
)

image

melted = pd.melt(df, id_vars=['Year'], value_vars=['Difference', 'Missing'])


alt.Chart(
    data=melted,
    background='white'          
).mark_bar(
).encode(
    alt.X('Year:O', title=''),
    alt.Y('value:Q', title=''),
    alt.Color('variable:N', 
              scale=alt.Scale(domain=['Difference', 'Missing'],
                              range=[sand, red])),
    order=alt.Order('variable', sort='descending')
)

In the plot below I have the chart I want but the Legend says Difference and I would rather it say Total. I know I can change the original column names or the values within the melted dataframe, but I was hoping for a cleaner way to change the legend labels.

image

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
jakevdpcommented, Jun 18, 2020

You can use the legend values setting to specify a subset of the range to show in the legend; you can’t use it to change the scale range to contain different values. Here’s an example of how it’s intended to be used:

import altair as alt
import pandas as pd

df = pd.DataFrame({'Year': [2014, 2015, 2016, 2017, 2018, 2019],
 'Total': [376, 1198, 1871, 4386, 4920, 2417],
 'Missing': [299, 758, 1063, 233, 32, 11],
 'Difference': [77, 440, 808, 4153, 4888, 2406]}
)

alt.Chart(df).transform_fold(
    ['Total', 'Missing'],
    as_=['variable', 'value']
).mark_bar().encode(
    alt.X('Year:O', title=''),
    alt.Y('value:Q', title='', stack=None),
    alt.Color('variable:N', 
              scale=alt.Scale(domain=['Total', 'Missing'],
                              range=['#ddccbb', 'red']),
              legend=alt.Legend(values=['Total'])),
    order=alt.Order('variable:N', sort='descending')
).properties(
    background='white'
)

visualization - 2020-06-17T223818 781

2reactions
jakevdpcommented, Jul 3, 2019

Another more slick option would be to actually use your Total entry and set stack=None to create an unstacked bar chart (here I use a fold transform in the chart rather than a pd.melt external to the chart)

import altair as alt
import pandas as pd

df = pd.DataFrame({'Year': [2014, 2015, 2016, 2017, 2018, 2019],
 'Total': [376, 1198, 1871, 4386, 4920, 2417],
 'Missing': [299, 758, 1063, 233, 32, 11],
 'Difference': [77, 440, 808, 4153, 4888, 2406]}
)

alt.Chart(df).transform_fold(
    ['Total', 'Missing'],
    as_=['variable', 'value']
).mark_bar().encode(
    alt.X('Year:O', title=''),
    alt.Y('value:Q', title='', stack=None),
    alt.Color('variable:N', 
              scale=alt.Scale(domain=['Total', 'Missing'],
                              range=['#ddccbb', 'red'])),
    order=alt.Order('variable:N', sort='descending')
).properties(
    background='white'
)

visualization (35)

Read more comments on GitHub >

github_iconTop Results From Across the Web

Is it possible to add a string as a legend item in matplotlib
Sure. ax.legend() has a two argument form that accepts a list of objects (handles) and a list of strings (labels). Use a dummy...
Read more >
Composing Custom Legends — Matplotlib 3.6.2 documentation
No artists with labels found to put in legend. Note that artists whose label start with an underscore are ignored when legend() is...
Read more >
Custom legends in Matplotlib - Python Graph Gallery
This post explains how to customize the legend on a chart with matplotlib. It provides many examples covering the most common use cases...
Read more >
GGPlot Legend Title, Position and Labels - Datanovia
It's possible to use the function guides () to set or remove the legend of a particular aesthetic (fill, color, size, shape, etc)....
Read more >
Swap LEGEND for LABELS I Dynamically LABEL LINE ...
In this video I show you how to do dynamically label line chart series in Power BI instead of adding a legend to...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found