'Pandas bar plot x axis stuck on wrong column

I want to plot a bar plot from pandas dataframe and have a reasonable amount of xticks.

My dataframe (data) looks like this:

0  Channel  Counts  Energy [keV]
0        1       0         -0.02
0        2       0          0.01
0        3       0          0.04 
...
2     2044       2         58.81
1     2045       1         58.83
[2048 rows x 4 columns]

I'm plotting the bar plot with x = data["Energy [keV]"] and height = data["Counts"] and whatever I try I get either:

  • All 2048 energy values with labels which become a jumbled mess
  • First 50 (for example) energy values jumbled together at the beginning of the x-axis

Basically the plot is plotting the position of the bars right (using the energy values) and when I try to manipulate ticks, or add a vertical line it always uses 0 to 2048 x axis.

What I get is that: plot with jumbled values (too many ticks)

Code:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

tmp = {'Channel': np.arange(1, 2049, 1),'Energy [keV]': np.arange(1, 2049, 1),
       'Counts': np.random.rand(2048)*1000}
data = pd.DataFrame(tmp)
data['Energy [keV]'] = -0.048 + 0.029*data['Channel']

fig4 = plt.figure(figsize=(16,8))
ax4 = fig4.add_subplot(1, 1, 1)

data.plot.bar(x = "Energy [keV]", y = "Counts", width=1, ax=ax4, align='center')
ax4.vlines(x=25.0, ymin = ylim_min, ymax = ylim_max, color = 'darkred')

I tried couple of solutions including converting the columns into numpy arrays, changing dataframe index, xaxis.set_ticks, xaxis.set_major_formatter... but something is always wrong.

I want to have nice, round ticks like 5.0, 10.0, 15.0, and when I make vline at x=25.0 that it would actually be at the value of 25.0. In the code I created a random number of counts so the snippet will be easier to recreate.



Solution 1:[1]

Have you tried ax4.bar(data["Energy [keV]"], data["Counts"], width=1, align='center')?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Z Li