3

I have been using altair for a time and this is the first time that I have experienced this issue, I have this simple code:

import pandas as pd
import altair as alt

# extract data into a nested list
data = {
        "Name of District": ["Kollam", "Beed", "Kalahandi", "West Medinipur", "Birbhum", "Howrah"],
        "No. of Cases": [19, 11, 42, 145, 199, 85],
    }

# create a dataframe from the extracted data
df = pd.DataFrame(
    data
)

# Display the first 5 rows
print(df.head().to_markdown(index=False, numalign="left", stralign="left"))

# Create a bar chart with `Name of District` on the x-axis and `No. of Cases` on the y-axis
chart = alt.Chart(df).mark_bar().encode(
    x='Name of District',
    y='No. of Cases',
    tooltip=['Name of District', 'No. of Cases']
).properties(
    title='Bar Chart of No. of Cases by Name of District'
).interactive()

# Save the chart
chart.save('no_of_cases_by_name_of_district_bar_chart.json')
display(chart)

it returns this plot:

Altair plot

If I plot it using matplotlib, then i get the correct plot:

Matplotlib Plot

I have tried this on colab and on my local machine and I have gotten the same results, why could this happen?

1 Answer 1

2

Altair requires that special characters be escaped in the column names. See documentation here.

This code should produce the plot you're looking for.

chart = alt.Chart(df).mark_bar(
).encode(
    x='Name of District',
    y='No\. of Cases',
    tooltip=['Name of District', 'No\. of Cases']
).properties(
    title='Bar Chart of No. of Cases by Name of District'
).interactive()
1
  • thank you very much, I haven't noticed it before. Commented Jul 1 at 15:32

Not the answer you're looking for? Browse other questions tagged or ask your own question.