Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increasing bar width in bar chart using Altair

Tags:

python

altair

I have the following dataframe and want to use altair library in Python to plot my bar chart. However, I couldn't figure out how to expand the width of each bar (same as width=0.5 parameter in matplotlib).

import pandas as pd 
from altair import * 

ls = [[   1,  734], [   2, 1705], [   3, 2309],
      [   4, 2404], [   5, 2022], [   6, 1538],
      [   7, 1095], [   8,  770], [   9,  485],
      [  10,  312], [  11,  237], [  12,  153],
      [  13,  103], [  14,   69], [  15,   47],
      [  16,   39], [  17,   43], [  18,   28],
      [  19,   18]]
df = pd.DataFrame(ls, columns=['n_authors', 'n_posters'])

Here is plotting function using altair

bar_chart = Chart(df).mark_bar().encode(
    x=X('n_authors', title='Number of Authors in a Poster'), 
    y=Y('n_posters', title='Number of Posters'),
).configure_facet_cell(
    strokeWidth=1.0,
    height=200,
    width=300
 )
bar_chart.display()

The plot looks like below from the script:

Imgur

like image 225
titipata Avatar asked Sep 01 '17 17:09

titipata


People also ask

How do I increase the width of a bar chart bar?

Click on any bar in the Bar Chart and right click on it, then select Format Data Series from the right-clicking menu. See screenshot: 2. In the popping up Format Data Series pane, move the Zoom bar of the Gap Width to the left side until the bar width meets your needs under the Series Options section.

How do you widen a histogram bar?

Re: How to change width of bars in histogram? Hi, Right click on the graph body and select Customize > Select the "Bar" item and increase the "Width Proportion". Note, you may need to bump that number to 100 or even larger values if you have a lot of data.


2 Answers

The answer of @Nipun doesn't work any more. After some experimenting, I could obtain the desired result with size instead of barSize. (I only tested it in Jupyter Lab.)

from pandas import *
from altair import *

ls = [[   1,  734], [   2, 1705], [   3, 2309],
      [   4, 2404], [   5, 2022], [   6, 1538],
      [   7, 1095], [   8,  770], [   9,  485],]
df = DataFrame(ls, columns=['X', 'Y'])

Chart(df).mark_bar(size=20).encode(x='X', y='Y')
like image 103
Primo Petri Avatar answered Sep 20 '22 06:09

Primo Petri


You need to use the barSize argument. See more here for Mark Configuration.

Solution

bar_chart = Chart(df).mark_bar(barSize=20).encode(
    x=X('n_authors', title='Number of Authors in a Poster'), 
    y=Y('n_posters', title='Number of Posters'),
).configure_facet_cell(
    strokeWidth=1.0,
    height=200,
    width=300
 )
bar_chart.display()

Output

enter image description here

like image 26
Nipun Batra Avatar answered Sep 20 '22 06:09

Nipun Batra