1

I would like to plot a histogram in which x-axis will contains ordered tuple data and y-axis will contains its frequencies. A CSV file containing data as follows :

x_values    y_frequency
(2,102,100) 6
(2,255,100) 30
(2,255,201) 76
(20,255,201)    102
(220,255,201)   34
(171,255,201)   47    

I have tried with the following code, but it does not give the correct histogram.

\documentclass{article}
%\usepackage{pgfplots}
%\usepackage{filecontents}
\usepackage{filecontents}
\usepackage{pgfplots, pgfplotstable}
\usepgfplotslibrary{statistics}

\begin{document}
\begin{tikzpicture}
\begin{axis}[
ybar,
ymin=0
]
    \addplot +[
hist={
    bins=7,
    data min=0.5,
    %data max=4
}   
] table [x=x_values, y=y_frequency, col sep=tab] {data.csv};
\end{axis}
\end{tikzpicture}
\end{document}  

Here is the CSV file data.csv :

x_values    y_frequency
2   3
4   9
8   1
0   5
Primo Raj
  • 107

1 Answers1

2

Here is a proposal to get the coordinates in.

\documentclass{article}
\usepackage{filecontents}
\begin{filecontents*}{data.csv}
x_values    y_frequency
(2,102,100) 6
(2,255,100) 30
(2,255,201) 76
(20,255,201)    102
(220,255,201)   34
(171,255,201)   47    
\end{filecontents*}
\usepackage{pgfplots, pgfplotstable}
\usepgfplotslibrary{statistics}
\pgfplotsset{compat=1.16}
% from https://tex.stackexchange.com/a/445369/121799
\newcommand*{\ReadOutElement}[4]{%
    \pgfplotstablegetelem{#2}{#3}\of{#1}%
    \let#4\pgfplotsretval
}
\begin{document}
\pgfplotstableread[header=true]{data.csv}\datatable
\pgfplotstablegetrowsof{\datatable}
\pgfmathtruncatemacro{\rownum}{\pgfplotsretval-1}
\foreach \X in {0,...,\rownum}
{\ReadOutElement{\datatable}{\X}{x_values}{\tmpx}
\ifnum\X=0
\xdef\lstSymbCoords{{\tmpx}}
\else
\xdef\lstSymbCoords{\lstSymbCoords,{\tmpx}}
\fi}
%\typeout{\lstSymbCoords}
\begin{tikzpicture}
\edef\temp{\noexpand\begin{axis}[
ybar,
ymin=0,
symbolic x coords={\lstSymbCoords},
 xticklabel style={
        rotate=90,
        anchor=east}
]}
\temp
\addplot[
% hist={
%     bins=7,
%     data min=0.5,
%     %data max=4
% }   
] table [x=x_values,y=y_frequency] {\datatable};
\end{axis}
\end{tikzpicture}
\end{document}  

enter image description here