How to create a “Split-Bars” plot in Python?

In the datawrapper.de visualizations service a “Split-Bars” plot is available; and I would like to recreate that visualization plot type (programmatically) in Python using matplotlib (etc).

enter image description here

No related questions were found on SO.

Problem Description: The structure seems to be table format; with each cell filled with a shaded area; to a given filled-percentage. Axis lines are removed. Value-text colors change depending on background color. Value-text positions change depending on % value.

Attempts: ChatGPT recommended ax.imshow() to generate each cell with colors, but (AFAIK) it lacks %-filled functionality.I reverted to ax.fill_between(), however that only works to a line along the axis (X or Y). Finally I tried ax.add_patch(Rectangle(...)), which seems to be the ideal choice the outer ‘legend’ color patches and the inner ax %-filled color-patches. Solution using this approach shown below.

Library code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.patches import Rectangle
import matplotlib.font_manager as font_manager
# Add every font at the specified location
font_dir = ['path/to/AppData/Local/Microsoft/Windows/Fonts/']
for font in font_manager.findSystemFonts(font_dir):
font_manager.fontManager.addfont(font)
from matplotlib.font_manager import findfont, FontProperties
font = findfont(FontProperties(family=['Roboto']))
matplotlib.rcParams['font.family'] = 'sans-serif'
matplotlib.rcParams['font.sans-serif'] = 'Roboto'
def plot_split_bar(data, metrics, categories,
colors=[(0.6431, 0.9412, 1.0),
(0.0, 0.6392, 0.6902),
(0.0, 0.349, 0.3765),
(0.2039, 0.749, 0.8118),
(0.0, 0.4392, 0.4745),
(0.3686, 0.8549, 0.9255),
(0.0, 0.5373, 0.5804)],
precision=2, fig_size=None):
numrows = data.shape[0]
numcols = data.shape[1]
data_max = np.max(data)*1.025
fig, ax = plt.subplots()
if fig_size:
fig.set_size_inches(fig_size)
# Set labels and ticks
ax.set_xticks(np.arange(len(categories))-0.14)
ax.set_xticklabels(categories, fontsize=8, fontname='Roboto', ha='left', va='center', y=1.001, weight='bold')
ax.xaxis.tick_top()
ax.xaxis.set_ticks_position('none')
ax.set_yticks(np.arange(len(metrics))+0.26)
ax.set_yticklabels(metrics, fontsize=7, fontname='Roboto', x=0.025, ha='right')
ax.spines[['right', 'top','bottom','left']].set_visible(False)
# Add text annotation
for i in range(len(data)):
for j in range(len(data[i])):
perc = data[i][j]/data_max
ax.add_patch(Rectangle((j-.29, i-.25), perc, 0.95,
facecolor = colors[j],
alpha=1,
fill=True,
))
text_pos = (j-0.26)+perc if perc < 0.5 else (j-(0.26)+.1)
text_col = '#333' if perc < 0.5 else 'white'
text_col = '#333' if text_col=='white' and np.mean(colors[j])>0.5 else text_col
text_bold = None if perc < 0.5 else 'bold'
text_perc = f'{data[i][j]:,.{precision}f}' if f'{data[i][j]:,.1f}'[-2:]!='.0' else f'{data[i][j]:,.0f}'
ax.text(text_pos, i+.15, text_perc, ha='left', va='center',
fontname='Roboto', color=text_col, fontsize=7, weight=text_bold)
ax.grid(False)
ax.set_ylim(0-0.5, numrows)
ax.set_xlim(0-0.5, numcols)
for j in range(len(categories)):
ax.add_patch(Rectangle((j-0.31, len(data)+.4), 0.15, .7,
facecolor = colors[j],
clip_on=False,
alpha=1,
fill=True,
))
plt.show()
</code>
<code>import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap from matplotlib.patches import Rectangle import matplotlib.font_manager as font_manager # Add every font at the specified location font_dir = ['path/to/AppData/Local/Microsoft/Windows/Fonts/'] for font in font_manager.findSystemFonts(font_dir): font_manager.fontManager.addfont(font) from matplotlib.font_manager import findfont, FontProperties font = findfont(FontProperties(family=['Roboto'])) matplotlib.rcParams['font.family'] = 'sans-serif' matplotlib.rcParams['font.sans-serif'] = 'Roboto' def plot_split_bar(data, metrics, categories, colors=[(0.6431, 0.9412, 1.0), (0.0, 0.6392, 0.6902), (0.0, 0.349, 0.3765), (0.2039, 0.749, 0.8118), (0.0, 0.4392, 0.4745), (0.3686, 0.8549, 0.9255), (0.0, 0.5373, 0.5804)], precision=2, fig_size=None): numrows = data.shape[0] numcols = data.shape[1] data_max = np.max(data)*1.025 fig, ax = plt.subplots() if fig_size: fig.set_size_inches(fig_size) # Set labels and ticks ax.set_xticks(np.arange(len(categories))-0.14) ax.set_xticklabels(categories, fontsize=8, fontname='Roboto', ha='left', va='center', y=1.001, weight='bold') ax.xaxis.tick_top() ax.xaxis.set_ticks_position('none') ax.set_yticks(np.arange(len(metrics))+0.26) ax.set_yticklabels(metrics, fontsize=7, fontname='Roboto', x=0.025, ha='right') ax.spines[['right', 'top','bottom','left']].set_visible(False) # Add text annotation for i in range(len(data)): for j in range(len(data[i])): perc = data[i][j]/data_max ax.add_patch(Rectangle((j-.29, i-.25), perc, 0.95, facecolor = colors[j], alpha=1, fill=True, )) text_pos = (j-0.26)+perc if perc < 0.5 else (j-(0.26)+.1) text_col = '#333' if perc < 0.5 else 'white' text_col = '#333' if text_col=='white' and np.mean(colors[j])>0.5 else text_col text_bold = None if perc < 0.5 else 'bold' text_perc = f'{data[i][j]:,.{precision}f}' if f'{data[i][j]:,.1f}'[-2:]!='.0' else f'{data[i][j]:,.0f}' ax.text(text_pos, i+.15, text_perc, ha='left', va='center', fontname='Roboto', color=text_col, fontsize=7, weight=text_bold) ax.grid(False) ax.set_ylim(0-0.5, numrows) ax.set_xlim(0-0.5, numcols) for j in range(len(categories)): ax.add_patch(Rectangle((j-0.31, len(data)+.4), 0.15, .7, facecolor = colors[j], clip_on=False, alpha=1, fill=True, )) plt.show() </code>
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.patches import Rectangle
import matplotlib.font_manager as font_manager

# Add every font at the specified location
font_dir = ['path/to/AppData/Local/Microsoft/Windows/Fonts/']
for font in font_manager.findSystemFonts(font_dir):
    font_manager.fontManager.addfont(font)    
from matplotlib.font_manager import findfont, FontProperties
font = findfont(FontProperties(family=['Roboto']))
matplotlib.rcParams['font.family'] = 'sans-serif'
matplotlib.rcParams['font.sans-serif'] = 'Roboto'


def plot_split_bar(data, metrics, categories, 
                   colors=[(0.6431, 0.9412, 1.0),
                         (0.0, 0.6392, 0.6902),
                         (0.0, 0.349, 0.3765),
                         (0.2039, 0.749, 0.8118),
                         (0.0, 0.4392, 0.4745),
                         (0.3686, 0.8549, 0.9255),
                         (0.0, 0.5373, 0.5804)], 
                   precision=2, fig_size=None):


    numrows = data.shape[0]
    numcols = data.shape[1]
    data_max = np.max(data)*1.025
    fig, ax = plt.subplots()
    if fig_size:
        fig.set_size_inches(fig_size)
    # Set labels and ticks
    ax.set_xticks(np.arange(len(categories))-0.14)
    ax.set_xticklabels(categories, fontsize=8, fontname='Roboto', ha='left', va='center', y=1.001, weight='bold')
    ax.xaxis.tick_top()
    ax.xaxis.set_ticks_position('none') 
    ax.set_yticks(np.arange(len(metrics))+0.26)
    ax.set_yticklabels(metrics, fontsize=7, fontname='Roboto', x=0.025, ha='right')
    ax.spines[['right', 'top','bottom','left']].set_visible(False)
    
    # Add text annotation
    for i in range(len(data)):
        for j in range(len(data[i])):
            perc = data[i][j]/data_max
            ax.add_patch(Rectangle((j-.29, i-.25), perc, 0.95,
                                     facecolor = colors[j],
                                     alpha=1,
                                     fill=True,
                                  ))
            text_pos = (j-0.26)+perc if perc < 0.5 else (j-(0.26)+.1)
            text_col = '#333' if perc < 0.5 else 'white'
            text_col = '#333' if text_col=='white' and np.mean(colors[j])>0.5 else text_col
            text_bold = None if perc < 0.5 else 'bold'
            text_perc = f'{data[i][j]:,.{precision}f}' if f'{data[i][j]:,.1f}'[-2:]!='.0' else f'{data[i][j]:,.0f}'
            ax.text(text_pos, i+.15, text_perc, ha='left', va='center', 
                    fontname='Roboto', color=text_col, fontsize=7, weight=text_bold)
    ax.grid(False)
    ax.set_ylim(0-0.5, numrows)
    ax.set_xlim(0-0.5, numcols)
    
    for j in range(len(categories)):
        ax.add_patch(Rectangle((j-0.31, len(data)+.4), 0.15, .7,
                                 facecolor = colors[j],
                                 clip_on=False,
                                 alpha=1,
                                 fill=True,
                              ))
    plt.show()

Usage with Global CO2 emissions from fossil-fuel data:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>data = pd.DataFrame(arr[1:],columns=arr[0] ).set_index('year').iloc[::-1]
plot_split_bar(data=data.astype(float).to_numpy(),
metrics=data.index.tolist(),
categories=data.columns,
precision=2,
fig_size=(5, 3)
)
</code>
<code>data = pd.DataFrame(arr[1:],columns=arr[0] ).set_index('year').iloc[::-1] plot_split_bar(data=data.astype(float).to_numpy(), metrics=data.index.tolist(), categories=data.columns, precision=2, fig_size=(5, 3) ) </code>
data = pd.DataFrame(arr[1:],columns=arr[0] ).set_index('year').iloc[::-1]
plot_split_bar(data=data.astype(float).to_numpy(), 
               metrics=data.index.tolist(), 
               categories=data.columns, 
               precision=2,
               fig_size=(5, 3)
              )

enter image description here

Usage with Pseudorandom generated data:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>cols = 3
data = pd.DataFrame( np.random.rand(5,cols), columns=[chr(65+i) for i in range(cols)]).iloc[::-1]
plot_split_bar(data=data.to_numpy(),
metrics=data.index.tolist(),
categories=data.columns,
precision=2,
fig_size=(5, 1)
)
</code>
<code>cols = 3 data = pd.DataFrame( np.random.rand(5,cols), columns=[chr(65+i) for i in range(cols)]).iloc[::-1] plot_split_bar(data=data.to_numpy(), metrics=data.index.tolist(), categories=data.columns, precision=2, fig_size=(5, 1) ) </code>
cols = 3
data = pd.DataFrame( np.random.rand(5,cols), columns=[chr(65+i) for i in range(cols)]).iloc[::-1]
plot_split_bar(data=data.to_numpy(), 
               metrics=data.index.tolist(), 
               categories=data.columns, 
               precision=2,
               fig_size=(5, 1)
              )

enter image description here

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật