Skip to content
Advertisement

Change bubble size in altair without changing font size

I am trying to create a altair bubble chart. The sample code and sample dataframe is below: I want the size of the bubble based on Market_cap and put names of companies alongside. The problem is font size of names is also changing as per the bubble size.

How can this I create this bubble chart with different bubble size but same size of font for Company names?

df = pd.DataFrame({ 'Company' : ['Apple', 'Microsoft', 'Meta', 'Nvidia'],
                   'Rev_perct' : [30, 50, 90, 10],
                  'Score' : [8, 5, 10, 4],
                  'Market_Cap' : [2000, 1000, 500, 800]
})

Graph_1 = alt.Chart(df).mark_circle(size = 100).encode( y = alt.Y('Rev_perct'), x = alt.X('Score'), 
                                                       color=alt.condition(
                                                       "datum.Rev_perct > 30"
                                                       "& datum.Score > 6",  
                                                        alt.value('red'),     
                                                       alt.value('green')          
                                                       ), size='Market_Cap')

Text_1 = Graph_1.mark_text( align='center',
   baseline='line-top', color = 'black', fontSize = 12, angle = 0,
   dy=10, dx= -5    
).encode(text='Company:O')

(Graph_1 + Text_1).properties(width = 800, height = 400)

This is the resulting graph i am getting now- enter image description here

Advertisement

Answer

This is happening because your are building the mark_text chart from the mark_circle chart where you specified the size encoding, so it is inherited for the text. Either change the order in which you create the plots or unset the size encoding by passing the corresponding empty Altair encoding class (alt.Size()) in this case:

Text_1 = Graph_1.mark_text(
    align='center',
    baseline='line-top',
    color='black',
    fontSize=12,
    angle=0,
    dy=10,
    dx= -5    
).encode(
    text='Company:O',
    size=alt.Size()
)

enter image description here

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement