ericg
ericg

Reputation: 8722

Simple line graph with altair

I have a pandas dataframe that looks like:

        Difference
months  
Jan     7552
Feb     8080
Mar     7707
Apr     7718
May     13895
Jun     14423
Jul     14375
Aug     11898
Sep     12326
Oct     12211
Nov     12739
Dec     12927

difference.index

Index(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
       'Nov', 'Dec'],
      dtype='object', name='months')

difference.columns

Index(['Difference'], dtype='object')

I simply want a line graph where the y-axis represents the numeric values in the Difference column and each tick on the x-axis represents a month of the year.

This should be very close to what I want, but I am not sure how to assign x properly. I thought I should be able to do x = 'months' or x = difference.index, but that is an error.

alt.Chart( difference ).mark_line().encode(
    y = 'Difference',
    x = ???
)

Upvotes: 2

Views: 3788

Answers (1)

jakevdp
jakevdp

Reputation: 86320

Depending on how your data is stored, you can do a number of things.

Assuming your months are stored in a column of time-stamps, you can do something like this, using the month TimeUnit to extract just the month from the time-stamp:

import pandas as pd
import altair as alt

df = pd.DataFrame({'months': pd.date_range('2018-01-01', periods=12, freq='M'),
                   'Difference': [7552, 8080, 7707, 7718, 13895, 14423, 14375,
                                  11898, 12326, 12211, 12739, 12927]})

alt.Chart(df).mark_line().encode(
    x='month(months):T',
    y='Difference'
)

enter image description here

Upvotes: 3

Related Questions