mmv456
mmv456

Reputation: 13

How to create dynamic altair x-axis and not fixed on current values?

My data looks like this:

Name Date 1% 2% 10% ... 100%
Anne 1/1/24 3 5 1 ... 92
Anne 1/2/24 4 8 2 ... 78
Anne 1/3/24 7 9 6 ... 47

My x axis are the percentages: 1%, 2%, 5%, 10%, 15%, 25%, 50%, and 100%

I created my table using altair:

import altair as alt

chart_df = newdf.drop(columns = ['NAME'])
chart_df = chart_df.astype({col: 'float' for col in chart_df.columns if col != 'DATE'})

numeric_cols = sorted(chart_df.columns[1:].to_list(), key=float)

chart_df = chart_df[['DATE'] + numeric_cols]

chart_df['DATE'] = pd.to_datetime(chart_df['DATE'], format='%Y.%m.%d')
chart_df = chart_df.melt(id_vars = ['DATE'], var_name = '%age', value_name = 'Output')

chart_df['DATE'] = chart_df['DATE'].dt.strftime('%Y-%m-%d')

#st.write('Melted Dataframe:', chart_df)
chart = alt.Chart(chart_df).mark_circle(size = 60).encode(alt.X('%age:O', 
                                                                sort = numeric_cols),
                                                          alt.Y('Output:Q'),
                                                          color='DATE:N',
                                                          tooltip=['DATE:N', '%age:O', 'Output:Q']
                                                         ).properties(width = 600, height = 400)
st.altair_chart(chart, use_container_width = True)

This looks fine, but the x axis values are separated by a fixed distance instead of their actual values separated between the 0-100 range. The values at 1% and 2% should be located a lot closer than the values at 2% and 5%, however they're all separated by the same distance.

Here's what the chart looks like currently: Current Altair chart

And here's what it should look like with the values dynamically placed within the 0-100% domain: Goal Excel chart

Upvotes: 0

Views: 67

Answers (0)

Related Questions