Here is my data frame:
student | subject | current | previous |
---|---|---|---|
A | Math | 98 | 92 |
A | English | 88 | 94 |
B | Math | 68 | 71 |
B | English | 72 | 71 |
C | Math | 92 | 88 |
C | English | 92 | 84 |
I would like to plot a chart like this:
How would I do this in altair charts in python?
CodePudding user response:
You can just do
df.set_index(['student','subject']).plot.bar(rot=0)
CodePudding user response:
In the development version of Altair (installable from GitHub), you can use the new xOffset
property to recreate the chart you want:
import pandas as pd
import altair as alt
df = pd.DataFrame({
'student': ['A', 'A', 'B', 'B', 'C', 'C'],
'subject': ['Math', 'English', 'Math', 'English', 'Math', 'English'],
'current': [98, 88, 68, 72, 92, 92],
'previous': [92, 94, 71, 71, 88, 84],
}).melt(
id_vars=['student', 'subject'],
var_name='score_type',
value_name='score'
)
alt.Chart(df).mark_bar().encode(
x=alt.X('subject', title='', axis=alt.Axis(labelAngle=0)),
xOffset='score_type',
color=alt.Color('score_type', legend=alt.Legend(orient='bottom', title='')),
y='score',
column=alt.Column('student', header=alt.Header(orient='bottom', title=''))
)
Btw, try to post you data as text instead of a screenshot and it will be quicker for someone to help out since they can copy and paste it.