# Histogram Using Python View Node for KNIME 4.7

**URL:** <https://forum.knime.com/t/histogram-using-python-view-node-for-knime-4-7/66500>\
**Category:** KNIME Analytics Platform\
**Tags:** python, visualization\
**Created:** [May 2, 2023, 12:57pm UTC](https://forum.knime.com/t/histogram-using-python-view-node-for-knime-4-7/66500 "2023-05-02T12:57:06Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![HeatherPikairos](https://forum-cdn.knime.com/letter_avatar_proxy/v4/letter/h/a88e4f/32.png) [@HeatherPikairos](https://forum.knime.com/u/HeatherPikairos)\
**Post date:** [May 2, 2023, 12:57pm UTC](https://forum.knime.com/t/histogram-using-python-view-node-for-knime-4-7/66500/1 "2023-05-02T12:57:07Z")

</div>

Hello again 🙂

This is my third topic showing how to use -Matplotlib- in the -Python View- node in order to create visualisations. This time I’m sharing a workflow to plot 2 histograms, side by side, with different colours and numbers of bins. These parameters can be set in the component interactive view.

 ![image](https://forum-cdn.knime.com/uploads/default/original/3X/8/2/82997b3a4ad2d59bb2ccbcf81948c52b1c38be76.png)

I’ve posted my workflow to the hub, so please take a look:

> **[20230427 Pikairos Histogram Using Python View for KNIME 4.7 – heatherpikairos](https://hub.knime.com/heatherpikairos/spaces/Public/latest/Data%20Visualisation/Python/20230427%20Pikairos%20Histogram%20using%20Python%20View%20for%20KNIME%204.7~77-xq5uSI0sU40Mb)**
>
> Create Histograms using Matplotlib in the Python View node

Hope its useful!  
Heather

---

<div class="post-metadata">

**Author:** ![roberto\_cadili](https://forum-cdn.knime.com/user_avatar/forum.knime.com/roberto_cadili/32/62735_2.png) [@roberto\_cadili](https://forum.knime.com/u/roberto_cadili)\
**Post date:** [May 3, 2023, 7:26am UTC](https://forum.knime.com/t/histogram-using-python-view-node-for-knime-4-7/66500/2 "2023-05-03T07:26:54Z")

</div>

That’s excellent work, love it! Thanks for sharing it 🤩

---

<div class="post-metadata">

**Author:** ![HeatherPikairos](https://forum-cdn.knime.com/letter_avatar_proxy/v4/letter/h/a88e4f/32.png) [@HeatherPikairos](https://forum.knime.com/u/HeatherPikairos)\
**Post date:** [May 3, 2023, 10:39am UTC](https://forum.knime.com/t/histogram-using-python-view-node-for-knime-4-7/66500/3 "2023-05-03T10:39:36Z")

</div>

Thanks @Roberto 🙂 I’m happy to contribute to this community!

---

<div class="post-metadata">

**Author:** ![system](https://forum-cdn.knime.com/uploads/default/original/1X/ab3ccf34482a0329361734a18199390177204f15.png) [@system](https://forum.knime.com/u/system)\
**Post date:** [August 1, 2023, 10:39am UTC](https://forum.knime.com/t/histogram-using-python-view-node-for-knime-4-7/66500/4 "2023-08-01T10:39:38Z")

</div>

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.

---

<div class="post-metadata">

**Author:** ![ScottF](https://forum-cdn.knime.com/user_avatar/forum.knime.com/scottf/32/61316_2.png) [@ScottF](https://forum.knime.com/u/ScottF)\
**Post date:** [August 1, 2023, 3:45pm UTC](https://forum.knime.com/t/histogram-using-python-view-node-for-knime-4-7/66500/5 "2023-08-01T15:45:22Z")

</div>



---

<div class="post-metadata">

**Author:** ![HeatherPikairos](https://forum-cdn.knime.com/letter_avatar_proxy/v4/letter/h/a88e4f/32.png) [@HeatherPikairos](https://forum.knime.com/u/HeatherPikairos)\
**Post date:** [August 2, 2023, 2:30pm UTC](https://forum.knime.com/t/histogram-using-python-view-node-for-knime-4-7/66500/6 "2023-08-02T14:30:48Z")

</div>

Sharing the code so it can be more easily searched for 🙂

```auto
import knime.scripting.io as knio

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import colors
from matplotlib.ticker import PercentFormatter
import seaborn as sns
import pandas as pd
from io import BytesIO

# Get number of bins
n_bins1 = knio.flow_variables['Bins_Number_hist1']
n_bins2 = knio.flow_variables['Bins_Number_hist2']

# Get Data for the two histograms
x = knio.input_tables[0]['Dim1'].to_pandas()
y = knio.input_tables[0]['Dim2'].to_pandas()

# print(x)

# Create 2 subplots
fig, axs = plt.subplots(1, 2, tight_layout=True)
# Option if y axis should be shared: sharey=True # 

# Deal with Subplot 1 Percentage option plot
# N is the count in each bin, bins is the lower-limit of the bin
if knio.flow_variables['ordinate_hist1']=="percentage":
    # We can also normalize our inputs by the total number of counts
    N, bins, patches = axs[0].hist(x, bins=n_bins1, density=True, label=False, edgecolor='white', linewidth=1.2)
    
    # Now we format the y-axis to display percentage
    axs[0].yaxis.set_major_formatter(PercentFormatter(xmax=1))
    
    #density
    sns.kdeplot(x, ax=axs[0], legend = False)
else:
    N, bins, patches = axs[0].hist(x, bins=n_bins1, edgecolor='white', linewidth=1.2)

# Print Column Name as x label is subplot 1 
print( axs[0].set_xlabel( x.columns.values[0]))

# Deal with Subplot 2 Percentage option plot
if knio.flow_variables['ordinate_hist2']=="percentage":
    # We can also normalize our inputs by the total number of counts
    N2, bins2, patches2 = axs[1].hist(y, bins=n_bins2, density=True, label=False, edgecolor='white', linewidth=1.2)
    
    # Now we format the y-axis to display percentage
    axs[1].yaxis.set_major_formatter(PercentFormatter(xmax=1))
    
    #density
    sns.kdeplot(y, ax=axs[1], legend = False)
    
else:
    N2, bins2, patches2 = axs[1].hist(y, bins=n_bins2, label=False, edgecolor='white', linewidth=1.2)

# Print Column Name as x label is subplot 2 
print( axs[1].set_xlabel( y.columns.values[0]))

# Color code by height
fracs = N / N.max()
fracs2 = N2 / N2.max()

# Normalize the data to 0..1 for the full range of the colormap
norm = colors.Normalize(fracs.min(), fracs.max())
norm2 = colors.Normalize(fracs2.min(), fracs2.max())

# Loop through bins in histogram and set the color of each accordingly
# Subplot #1
for thisfrac, thispatch in zip(fracs, patches):
    if knio.flow_variables['colour_hist1']=="viridis":
        color = plt.cm.viridis(norm(thisfrac))
    if knio.flow_variables['colour_hist1']=="magma":
        color = plt.cm.magma(norm(thisfrac))
    if knio.flow_variables['colour_hist1']=="plasma":
        color = plt.cm.plasma(norm(thisfrac))
    if knio.flow_variables['colour_hist1']=="inferno":
        color = plt.cm.inferno(norm(thisfrac))
    if knio.flow_variables['colour_hist1']=="cividis":
        color = plt.cm.cividis(norm(thisfrac))
    thispatch.set_facecolor(color)

# The same for subplot #2
for thisfrac, thispatch in zip(fracs2, patches2):
    if knio.flow_variables['colour_hist2']=="viridis":
        color = plt.cm.viridis(norm(thisfrac))
    if knio.flow_variables['colour_hist2']=="magma":
        color = plt.cm.magma(norm(thisfrac))
    if knio.flow_variables['colour_hist2']=="plasma":
        color = plt.cm.plasma(norm(thisfrac))
    if knio.flow_variables['colour_hist2']=="inferno":
        color = plt.cm.inferno(norm(thisfrac))
    if knio.flow_variables['colour_hist2']=="cividis":
        color = plt.cm.cividis(norm(thisfrac))
    thispatch.set_facecolor(color)

## Create buffer to write into
buffer = BytesIO()

# Create plot and write it into the buffer
fig.savefig(buffer, format='svg')

# The output is the content of the buffer
output_image = buffer.getvalue()

# Assign the figure to the output_view variable
knio.output_view = knio.view(fig) # alternative: knio.view_matplotlib()

```

---

<div class="post-metadata">

**Author:** ![system](https://forum-cdn.knime.com/uploads/default/original/1X/ab3ccf34482a0329361734a18199390177204f15.png) [@system](https://forum.knime.com/u/system)\
**Post date:** [August 9, 2023, 2:31pm UTC](https://forum.knime.com/t/histogram-using-python-view-node-for-knime-4-7/66500/7 "2023-08-09T14:31:01Z")

</div>

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.
