Skip to content Skip to sidebar Skip to footer

How To Draw Bar Charts For Very Small Values In Python Or Matplotlib?

I drawn the comparison bar chart for very small values with the following code, import pandas as pd import matplotlib.pyplot as plt data = [[ 0.00790019035339353, 0.00002112],

Solution 1:

A common way to display data with different orders of magnitude is to use a logarithmic scaling for the y-axis. Below the logarithm to base 10 is used but other bases could be chosen.

import pandas as pd
import matplotlib.pyplot as plt

data = [[ 0.00790019035339353, 0.00002112],
        [0.0107705593109131, 0.0000328540802001953],
        [0.0507792949676514, 0.0000541210174560547]]

df = pd.DataFrame(data, columns=['A', 'B'])
df.plot.bar()

plt.yscale("log")
plt.show()

enter image description here

Update: To change the formatting of the yaxis labels an instance of ScalarFormatter can be used:

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter

data = [[ 0.00790019035339353, 0.00002112],
        [0.0107705593109131, 0.0000328540802001953],
        [0.0507792949676514, 0.0000541210174560547]]

df = pd.DataFrame(data, columns=['A', 'B'])
df.plot.bar()

plt.yscale("log")
plt.gca().yaxis.set_major_formatter(ScalarFormatter())
plt.show()

enter image description here

Solution 2:

You could create 2 y-axis like this:

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
width = 0.2
df['A'].plot(kind='bar', color='green', ax=ax1, width=width, position=1, label = 'A')
df['B'].plot(kind='bar', color='blue', ax=ax2, width=width, position=0, label = 'B')

ax1.set_ylabel('A')
ax2.set_ylabel('B')

# legend
h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()
ax1.legend(h1+h2, l1+l2, loc=2)

plt.show()

enter image description here

Post a Comment for "How To Draw Bar Charts For Very Small Values In Python Or Matplotlib?"