Issue
I have this data (dfe) that I want to plot in a histogram
Nr O18ad
0 -4.268475
1 -4.265793
2 -4.263120
3 -4.260457
4 -4.257803
...
359995 -7.813345
359996 -7.821394
359997 -7.773479
359998 -7.807605
359999 -7.797769
Here I have this code snippet: It is part of an 8 part figure hence the subfigure function
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
def plot_Diff(data):
fig = plt.figure(figsize=(10, 10))
ax =fig.add_subplot(423)
x= dfe['O18ad']
bins=[-20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1]
old_yticks = ax.get_yticks()
bin_counts, _, bars = plt.hist(x, bins, alpha=0.65, label='old', edgecolor='black', color='lightgrey')
new_max_tick = bin_counts.max()
old_yticks = ax.get_yticks()
new_ticks = old_yticks[old_yticks < new_max_tick][:-1]
new_ticks = np.append(new_ticks, new_max_tick)
ax.set_yticks(new_ticks)
manual_ticks=[0,20_000]
if manual_ticks is None:
old_yticks = ax.get_yticks()
new_ticks = old_yticks[old_yticks < new_max_tick][:-1]
new_ticks = np.append(new_ticks, new_max_tick)
else:
new_ticks = np.append(manual_ticks, new_max_tick)
ax.set_yticks(new_ticks)
plt.show()
My output looks like this:
Now my question is how can I change the X axis ticks so that the maximum values (in this example 0) are automatically set in the right corner and the displayed minimum (in this example -20) values are in the left corner?
It is important that the max and min values are set automatically because I have about 100 histograms where I cannot always set them manually.
Solution
If I understand correctly, you want to find the left edge of the leftmost non-empty bin, and similarly at the right.
When bins
is a numpy array of bin edges, the left edges are bins[:-1]
(first till next to last edge), while the right edges are bins[1:]
(second till last edge). As bin_counts
is also a numpy array, you can index with [bin_counts > 0]
to filter out the non-empty bins. The obtained min and max will serve as the axis limits.
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
dfe = pd.DataFrame({'O18ad': np.random.normal(0.01, 0.1, 1000).cumsum()})
dfe['O18ad'] -= dfe['O18ad'].max() + np.random.uniform(0.1, 5)
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111)
x = dfe['O18ad']
bins = np.arange(-20, 2)
old_yticks = ax.get_yticks()
bin_counts, _, bars = plt.hist(x, bins, alpha=0.65, label='old', edgecolor='black', color='lightgrey')
new_max_tick = bin_counts.max()
print(bins[:-1][bin_counts > 0].min())
print(bins[1:][bin_counts > 0].max())
ax.set_xlim(bins[:-1][bin_counts > 0].min(), bins[1:][bin_counts > 0].max())
plt.show()
Answered By - JohanC
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.