0

Using Altair, how can I plot in the same horizontal bar plot two variables that are in the same data frame?

I have a panda data frame that looks like this:

# initialize list of lists
data = [['AAA','71.15','FOUSA06C1Y'],
['AA','2.93','FOUSA06C1Y'],
['A','11.9','FOUSA06C1Y'],
['BBB','14.04','FOUSA06C1Y'],
['BB','0.0','FOUSA06C1Y'],
['B','0.0','FOUSA06C1Y'],
['Below B','0.0','FOUSA06C1Y'],
['Not Rated','-0.02','FOUSA06C1Y'],
['AAA','34.81744518','1404'],
['AA','47.24845367','1404'],
['A','16.66257244','1404'],
['BBB','1.271528716','1404'],
['BB / B','0.0','1404'],
['Below B','0.0','1404'],
['Short Term Rated','0.0','1404'],
['Not Rated','0.0','1404'],
['Nan','0.0','1404']]
  
# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['index', 'value','fund'])

df['value'] = df['value'].astype(float)

I am able to separately horizontal bar plot these with below code:

gp_chart = alt.Chart(df).mark_bar().encode(
    alt.X('value'),
    alt.Y('index', axis=alt.Axis(grid=True)), 
    alt.Color('fund'),
    alt.Row('fund')
    )

gp_chart

Which will produce this separated graphs:

enter image description here

Picking part of this graph as an example (just picking A and AAA), I want to see these bars together like this: enter image description here

Similar question here.

FFLS
  • 565
  • 1
  • 4
  • 19

1 Answers1

1

I lack experience with altair, but I can use the filter function to create a graph with only positive values by setting the values above and below 0 and non-zero.

import altair as alt
from altair import datum

gp_chart = alt.Chart(df).mark_bar().encode(
    alt.X('value'),
    alt.Y('index', axis=alt.Axis(grid=True)), 
    alt.Color('fund'),
    alt.Row('fund')
    ).transform_filter(
    (datum.value != 0) & (datum.value >= 0)
)

gp_chart

enter image description here

New Version 5.0.0rc1 Although not officially released yet, it appears that grouping is possible with the latest version of the functionality. See this page

pip install altair==5.0.0rc1
import altair as alt
from altair import datum

gp_chart = alt.Chart(df).mark_bar().encode(
    alt.X('value'),
    alt.Y('index', axis=alt.Axis(grid=True)), 
    alt.Color('fund'),
    yOffset='fund'
    ).transform_filter(
    (datum.value != 0) & (datum.value >= 0)
)

gp_chart

enter image description here

r-beginners
  • 31,170
  • 3
  • 14
  • 32
  • thanks for the answer, however, I need to have the orange and blue graph in the same frame/graph. For example, in order, I need to have A for the "1404" and then the A for the "FOUSA06C1Y", then AA for the "1404" and then the AA for the "FOUSA06C1Y" if that makes sense. – FFLS Apr 28 '23 at 12:33