MarcinBurz
MarcinBurz

Reputation: 347

Bars width are wrong using log scale of x-axis

I need log scale x-axis. Here is my code:

plt.bar(critical_pressures_reversed, mercury_volume_scaled, bottom = 0, log = True, linewidth=0, align="center",width=.1)
plt.title("Mercury intrusion", fontsize=20)
plt.xlabel("Critical Pressure $P_c \, [kPa]$", fontsize=16)
plt.ylabel("Mercury volume $V_m \, [\mu m^3]$", fontsize=16)
plt.grid(b=True, which='major', color='black', linestyle='-',  linewidth=1)
plt.grid(b=True, which='minor', color='gray', linestyle='-',  linewidth=0.15)
frame = plt.gca()
figure = plt.gcf()
frame.set_xscale('log')
frame.set_axisbelow(True)
figure.set_size_inches(12, 6)
plt.savefig("intrusion_6n_press.png", dpi=300, bbox_inches='tight')
plt.close()

Resulting plot:

Example of bar plot with log x-axis here

How to force pyplot to draw bars with constant width?

I am using matplotlib (1.4.2)

Upvotes: 0

Views: 2212

Answers (1)

giosans
giosans

Reputation: 1178

You could use plt.fill but the bar width should change based on the log. For instance, for a random dataset, the following lines:

import matplotlib.pyplot as plt
import numpy as np
x, y = np.random.randint(1,51,10), np.random.randint(1,51,10)
width = 1e-2
for i in range(len(x)):
    plt.fill([10**(np.log10(x[i])-width), 10**(np.log10(x[i])-width), 10**(np.log10(x[i])+width), 10**(np.log10(x[i])+width)],[0, y[i], y[i], 0], 'r', alpha=0.4)
plt.bar(x,y, bottom = 0, log = True, linewidth=0, align="center",width=.1, alpha=0.4)

will produce the figure below. Everything you need to do is to choose a proper width parameter. enter image description here

Upvotes: 2

Related Questions