changing x values when using histcounts

3 views (last 30 days)
sani
sani on 19 Mar 2020
Answered: Vedant Shah on 30 Jun 2025
Hi all
I'm trying present a spectrum in matlab, and I want to calibrate the x axis to the correct values (they losts when I using histcounts I belive). the lefe peak need to be 511 and the right one in 1460.
the scipt I'm using for this spectrum is:
[X,edges] = histcounts(Ge_table.energy,16384);
Z = histcounts(Ge_energy,edges);
semilogy(X,'r')
hold on
semilogy(Z,'b')
xlabel('Energy [keV]')
ylabel('Counts')

Answers (1)

Vedant Shah
Vedant Shah on 30 Jun 2025
Hi @sani,
When using semilogy(X, 'r'), the bin counts are plotted against the bin index rather than the actual energy value for each bin. To address this, I advise you to first calculate the bin centers to obtain the corresponding energy values and then use these values for plotting with the semilogy function.
Additionally, if the peaks do not appear at the expected energies, calibration is necessary. For instance, if the left peak is located at bin i1 and the right peak at bin i2, with current energy values E1 and E2 respectively, these should be mapped to 511 keV and 1460 keV.
The following sample code demonstrates this approach:
[X,edges] = histcounts(Ge_table.energy,16384);
Z = histcounts(Ge_energy,edges);
bin_centers = (edges(1:end-1) + edges(2:end)) / 2;
[peakVals,peakLocs] = findpeaks(X);
[~, sortIdx] = sort(bin_centers(peakLocs));
peakLocsSorted = peakLocs(sortIdx);
i1 = peakLocsSorted(1);
i2 = peakLocsSorted(end);
E1 = bin_centers(i1);
E2 = bin_centers(i2);
a = (1460 - 511) / (E2 - E1);
b = 511 - a * E1;
bin_centers_calibrated = a * bin_centers + b;
semilogy(bin_centers_calibrated, X, 'r')
hold on
semilogy(bin_centers_calibrated, Z, 'b')
xlabel('Energy [keV]')
ylabel('Counts')
legend('X spectrum','Z spectrum')
title('Calibrated Spectrum')
grid on
By following this procedure, the spectrum will be displayed with the x-axis correctly calibrated to the desired energy values, ensuring that the peaks appear at the specified energies as shown below:
For more information, refer to the following documentations:

Categories

Find more on Data Distribution Plots in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!