# 3-dimensional histogram in pgfplots

I have a simple 3d histogram

which I want to import into pgfplots, e.g. using matlab2tikz or by hand.

PGFplots does not offer 3d histograms.

Is there an easy way to do this?

-
3-D histograms convey very little information and can be misleading. Consider changing the plot to a different type. –  Yiannis Lazarides Apr 23 '12 at 13:28
You're both right, but where I'm using it the data itself is random and a 3d histogram puts an emphasis to the discrete nature of a rainflow matrix. –  severin Apr 23 '12 at 14:30
@severin: How did you manage to hide the bars with zero counts? –  Jake Apr 23 '12 at 18:39
@Jake They are probably having NaN values. –  percusse Apr 24 '12 at 0:20
@Jake: Yes, it's a colormap. I used a function (rfmatrix) which came with the rainflow package: mathworks.de/matlabcentral/fileexchange/… –  severin Apr 24 '12 at 12:12

You can use \addplot3 graphics to include an image in pgfplots. This allows you to use pgfplots for drawing the axes and to add annotations using the data coordinate system.

If you have saved a plot from Matlab as an image called 3dcolumnchart.png, for example, the following code

\addplot3 graphics[points={%
(-4.4449,4.6547,0) => (110.814,167.827)
(-4.633,-4.5186,0) => (264.187,74.679)
(4.5829,-4.5216,0) => (470.558,145.343)
(-0.45821,-0.43355,1157) => (287.474,379.016)
}] {3dcolumnchart.png};
\node at (axis cs:-1.5,0.5,490) [inner sep=0pt, pin={[pin edge={thick,black},align=left]145:Interesting\\Data Point}] {};


will generate

For this, you need to provide the mapping from the data coordinate system to the figure coordinate system for four points. You can do this by finding the data coordinates for the points using the "Data Cursor" in Matlab, and finding the figure coordinates (in pt) for the same points in an image editor like GIMP. However, this can quickly become a bit tedious.

I've written a Matlab script called pgfplotscsconversion.m that allows you to click on four points in the Matlab figure, and the mapping will be written to the Matlab command prompt.

Here's an example of how I arrived at the above figure.

1. Create the Matlab plot

hist3(randn(10000,2)) % some random data
set(get(gca,'child'),'FaceColor','interp','CDataMode','auto'); % colors
set(gcf,'PaperPositionMode','auto') % make sure the "print" paper format is the same as the screen paper format

2. Save the following code as pgfplotscsconversion.m

function pgfplotscsconversion

% Hook into the Data Cursor "click" event
h = datacursormode(gcf);
set(h,'UpdateFcn',@myupdatefcn,'SnapToDataVertex','off');
datacursormode on

% select four points in plot using mouse

% The function that gets called on each Data Cursor click
function [txt] = myupdatefcn(obj,event_obj)

% Get the screen resolution, in dots per inch
dpi = get(0,'ScreenPixelsPerInch');

% Get the click position in pixels, relative to the lower left of the
% screen
screen_location=get(0,'PointerLocation');

% Get the position of the plot window, relative to the lower left of
% the screen
figurePos = get(gcf,'Position');

% Get the data coordinates of the cursor
pos = get(event_obj,'Position');

% Format the data and figure coordinates. The factor "72.27/dpi" is
% necessary to convert from pixels to TeX points (72.27 poins per inch)
display(['(',num2str(pos(1)),',',num2str(pos(2)),',',num2str(pos(3)),') => (',num2str((screen_location(1)-figurePos(1))*72.27/dpi),',',num2str((screen_location(2)-figurePos(2))*72.27/dpi),')'])

% Format the tooltip display
txt = {['X: ',num2str(pos(1))],['Y: ',num2str(pos(2))],['Z: ',num2str(pos(3))]};


Run pgfplotscsconversion, click on four points in your plot. Preferably select non-colinear points near the edges of the plot. Copy and paste the four lines that were written to the Matlab command window.

3. Export the plot as an image

axis off
print -dpng matlabout -r400 % PNG called "matlabout.png" with 400 dpi resolution


If you want to use vector PDF output, you'll have to set the paper size to match the figure size yourself, since the PDF driver doesn't automatically adjust the size:

currentScreenUnits=get(gcf,'Units')     % Get current screen units
currentPaperUnits=get(gcf,'PaperUnits') % Get current paper units
set(gcf,'Units',currentPaperUnits)      % Set screen units to paper units
plotPosition=get(gcf,'Position')        % Get the figure position and size
set(gcf,'PaperSize',plotPosition(3:4))  % Set the paper size to the figure size
set(gcf,'Units',currentScreenUnits)     % Restore the screen units


4. Remove the white background of the image, for example using the ImageMagick command

convert matlabout.png -transparent white 3dcolumnchart.png

5. Include the image in your pgfplots axis. If you selected points on the plot corners, your xmin, xmax, ymin and ymax should be set automatically, otherwise you'll have to provide those yourself. Also, you'll need to adjust the width and height of the plot to get the right vertical placement of the plot.

\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}

\begin{document}
\begin{tikzpicture}
\begin{axis}[3d box,xmin=-5,xmax=5,ymin=-5,ymax=5,width=9cm,height=9.25cm,grid=both, minor z tick num=1]
(-4.4449,4.6547,0) => (110.814,167.827)
(-4.633,-4.5186,0) => (264.187,74.679)
(4.5829,-4.5216,0) => (470.558,145.343)
(-0.45821,-0.43355,1157) => (287.474,379.016)
}]
{3dcolumnchart.png};
\node at (axis cs:-1.5,0.5,490) [inner sep=0pt, pin={[pin edge={thick,black},align=left]145:Interesting\\Data Point}] {};
\end{axis}
\end{tikzpicture}
\end{document}

-
Yet another secret weapon! Quite nice. –  percusse Apr 23 '12 at 18:14
Good work! Would you mind if I copy your matlab script into the pgfplots manual? –  Christian Feuersänger Apr 23 '12 at 19:33
@ChristianFeuersänger: By all means, please do! I'd be honoured –  Jake Apr 24 '12 at 7:57
This is really nice. Unfortunately it does not quite seem to work with my example: imgur.com/CuAPy Is this because of the different domains? –  severin Apr 24 '12 at 18:56
@severin: You need to adjust the width and height values of your plot manually to make the axes start at zero. Also, something seems to be wrong with your grid lines. What axis options do you use? –  Jake Apr 24 '12 at 19:10

I managed to achieve a 3-dimensional histogram effect by repeating the coordinates. I just repeat each x,y combination 4 times, once for each of the 4 possible bar tops it could appear in.

For example, the code

\documentclass{minimal}
\usepackage{pgfplots}

\begin{document}
\begin{tikzpicture}
\begin{axis}[
view = {120}{35},% important to draw x,y in increasing order
xmin = 0,
ymin = 0,
xmax = 3,
ymax = 3,
zmin = 0,
unbounded coords = jump,
colormap={pos}{color(0cm)=(white); color(6cm)=(blue)}
]
(0,0,0) (0,0,0) (0,1,0) (0,1,0) (0,2,nan) (0,2,nan) (0,3,nan) (0,3,nan)

(0,0,0) (0,0,2) (0,1,2) (0,1,3) (0,2,3) (0,2,1) (0,3,1) (0,3,0)

(1,0,0) (1,0,2) (1,1,2) (1,1,3) (1,2,3) (1,2,1) (1,3,1) (1,3,0)

(1,0,0) (1,0,0) (1,1,0) (1,1,6) (1,2,6) (1,2,0) (1,3,0) (1,3,0)

(2,0,nan) (2,0,nan) (2,1,0) (2,1,6) (2,2,6) (2,2,0) (2,3,nan) (2,3,nan)

(2,0,0) (2,0,1) (2,1,1) (2,1,0) (2,2,0) (2,2,0) (2,3,nan) (2,3,nan)

(3,0,0) (3,0,1) (3,1,1) (3,1,0) (3,2,nan) (3,2,nan) (3,3,nan) (3,3,nan)

(3,0,0) (3,0,0) (3,1,0) (3,1,0) (3,2,nan) (3,2,nan) (3,3,nan) (3,3,nan)
};
\end{axis}
\end{tikzpicture}
\end{document}


produces

The 0 z-coordinate values above are meant to have the same value as zmin and the view has to be set such that the points with lower x and y coordinates are drawn first.

I don't know how to make the colour of the sides of the bars the same as the top, hence the monochrome colormap.

A larger example can be seen here

This is from some data I produced in python. To save it to a file, I had to add a few for loops that make sure all the points at the border are set to have z value equal to zmin. The function below takes the x, y mesh stored in x and y. The respective z values are in z, a list of len(x) - 1 lists of length len(y) - 1. It writes to a file output that can be included with \addplot3 file {}. It assumes that there are no NaN values and sets the z values along the border to zmin.

import csv

def make3dhistogram(x, y, z, zmin, output):
writer = csv.writer(open(output, 'wb'), delimiter=' ')
i = 0
for j in range(len(y)):
writer.writerow((x[i], y[j], zmin))
writer.writerow((x[i], y[j], zmin))
for i in range(len(x)-1):
writer.writerow((x[i], y[0], zmin))
for j in range(len(y)-1):
writer.writerow((x[i], y[j], z[i][j]))
writer.writerow((x[i], y[j+1], z[i][j]))
writer.writerow((x[i], y[len(y)-1], zmin))
writer.writerow([])
writer.writerow((x[i+1], y[0], zmin))
for j in range(len(y)-1):
writer.writerow((x[i+1], y[j], z[i][j]))
writer.writerow((x[i+1], y[j+1], z[i][j]))
writer.writerow((x[i+1], y[len(y)-1], zmin))
writer.writerow([])

i = len(x)-1
for j in range(len(y)):
writer.writerow((x[i], y[j], zmin))
writer.writerow((x[i], y[j], zmin))


So for example

x = [0,1,2,3]
y = [0,1,2,3]
z = [[2,3,1], [0, 6, 0], [1, 0, 0]]
make3dhistogram(x, y, z, 0.0, 'data')


produces the simple plot above, this time with a grid on the z plane as none of the points are skipped.

-
Wow, that's very impressive! I assume you didn't code the coordinates for the large plot by hand. Would you mind explaining how you generated the coordinates? –  Jake Apr 29 '12 at 20:00
You can get the sides in the same color as the top by using shader=flat corner. To get the connecting lines in a darker shade of the fill color, you can use draw=mapped color!80!black. –  Jake Apr 29 '12 at 20:13
Thank you @Jake. I added a brief description how I produced the input file from x,y,z values. –  anton Apr 29 '12 at 20:25
The Python code is not complete, could you please provide the missing parts? –  Uwe Ziegenhagen Apr 30 '12 at 5:24
@UweZiegenhagen I completed the code, I hope it's more clear now. –  anton Apr 30 '12 at 9:58

matlab2tikz now fully supports 3D histograms. This

load seamount
dat = [-y,x]; % Grid corrected for negative y-values
hist3(dat) % Draw histogram in 2D
n = hist3(dat); % Extract histogram data;
% default to 10x10 bins
view([-37.5, 30]);


gives

-
Oh wow, that's impressive! It works really well, even allowing arbitrary view parameters. The color can be improved a bit by setting shader=flat corner,draw=mapped color!70!black in the \addplot3 options. –  Jake May 2 '12 at 14:36
It seems that this approach struggles with the OP's use case, though: The size of 35x35 columns doesn't compile with pdflatex due to memory limitations, and compiling with lualatex (which works) reveals that there are z-buffering errors due to the reversed y axis. –  Jake May 2 '12 at 15:40
The z buffering problem is a bug in pgfplots; providing y dir=reverse will work well with the next pgfplots stable (i.e. not with 1.5.1). –  Christian Feuersänger May 2 '12 at 17:42
@Nico thanks for cool contribution! –  Christian Feuersänger May 2 '12 at 17:42
@Jake Oh this shouldn't happen. :/ Is the MATLAB code of the OP's figure out there? –  Nico Schlömer May 2 '12 at 17:43

I was not satisfied with the previous answers and therefore created my own solution.

• Jake's solution is present in the documentation but first I couldn't make it work, second it does not generate a image from data, which is what I want from Tikz.

• I worked on Anton's answer. It took me some time to figure out the way coordinates were organized to put it in a automatic code reading data from a file. But even if I managed to do so I couldn't overcome the impossibility to create a personalized coloring. I was then left with the choice between a monochrome plot like Anton shows, and a figure where the top face of a bar has a different color than its sides.

• I don't think that, as Nico said, matlab2tikz now fully supports 3D histograms, or I wouldn't have come here in the first place. I tried matlab2tikz on my picture given by matlab using 'bar3', and the result was bugged.

=> I offer a solution where I got rid of \begin{axis} and the constraints like \edef, \temp and \noexpand, that I had to use to make Anton's way work automatically.

Here is the minimal code :

\documentclass{minimal}
\usepackage{pgfplots}
\usepackage{pgfplotstable}

\begin{document}

\pgfplotstablegetrowsof{DataTest.dat}
\pgfmathtruncatemacro{\rows}{\pgfplotsretval-1}

\pgfplotstablegetelem{0}{[index] 2}\of{\firsttable}
\let\maxZ\pgfplotsretval
\pgfmathsetmacro{\Zscale}{4/\maxZ}

\begin{tikzpicture}[x={(0.866cm,-0.5cm)},y={(0.866cm,0.5cm)},z={(0cm,4 cm)}]

\colorlet{redhsb}[hsb]{red}     %
\colorlet{bluehsb}[hsb]{blue}   %

\foreach \p in {1,...,\rows}{
\pgfplotstablegetelem{\p}{[index] 0}\of{\firsttable}
\let\x\pgfplotsretval
\pgfplotstablegetelem{\p}{[index] 1}\of{\firsttable}
\let\y\pgfplotsretval
\pgfplotstablegetelem{\p}{[index] 2}\of{\firsttable}
\let\z\pgfplotsretval

\pgfmathtruncatemacro{\teinte}{100-((\z/\maxZ)*100)}
\colorlet{col}[rgb]{bluehsb!\teinte!redhsb}
% Visible faces from original view
\fill[col] (\x+0.5,\y+0.5,\z) -- (\x+0.5,\y-0.5,\z) -- (\x+0.5,\y-0.5,0) -- (\x+0.5,\y+0.5,0) -- (\x+0.5,\y+0.5,\z);
\draw[black](\x+0.5,\y+0.5,\z) -- (\x+0.5,\y-0.5,\z) -- (\x+0.5,\y-0.5,0) -- (\x+0.5,\y+0.5,0) -- (\x+0.5,\y+0.5,\z);
\fill[col] (\x+0.5,\y-0.5,\z) -- (\x-0.5,\y-0.5,\z) -- (\x-0.5,\y-0.5,0) -- (\x+0.5,\y-0.5,0) -- (\x+0.5,\y-0.5,\z);
\draw[black](\x+0.5,\y-0.5,\z) -- (\x-0.5,\y-0.5,\z) -- (\x-0.5,\y-0.5,0) -- (\x+0.5,\y-0.5,0) -- (\x+0.5,\y-0.5,\z);
% Top face
\fill[col] (\x-0.5,\y-0.5,\z) -- (\x-0.5,\y+0.5,\z) -- (\x+0.5,\y+0.5,\z) -- (\x+0.5,\y-0.5,\z) -- (\x-0.5,\y-0.5,\z) ;
\draw[black] (\x-0.5,\y-0.5,\z) -- (\x-0.5,\y+0.5,\z) -- (\x+0.5,\y+0.5,\z) -- (\x+0.5,\y-0.5,\z) -- (\x-0.5,\y-0.5,\z);
}

\end{tikzpicture}

\end{document}


Using the file DataTest.dat containing:

X   Y   Z
3   3   1   %max

1   3   1
1   2   0.8
1   1   0.7
2   3   0.75
2   2   0.5
2   1   0.25
3   3   0.3
3   2   0.1
3   1   0


Which gives the following picture :

To improve the picture and to have more comments on the code, here is a more detailed solution :

\documentclass{minimal}
\usepackage{pgfplots}
\usepackage{pgfplotstable}

\begin{document}

\pgfplotstablegetrowsof{DataTest.dat}
\pgfmathtruncatemacro{\rows}{\pgfplotsretval-1}       % Put the number of row minus one in \rows,
%     to use : \foreach \p in {0,...,\rows}
% Assign variables max
\pgfplotstablegetelem{0}{[index] 0}\of{\firsttable}
\let\maxX\pgfplotsretval
\pgfplotstablegetelem{0}{[index] 1}\of{\firsttable}
\let\maxY\pgfplotsretval
\pgfplotstablegetelem{0}{[index] 2}\of{\firsttable}
\let\maxZ\pgfplotsretval

\pgfmathsetmacro{\Zscale}{4/\maxZ} % contain the values of z between 0 and 4 cm
%      (provided that they are positiv)

% Defining by hand the axis
\begin{tikzpicture}[x={(0.866cm,-0.5cm)},y={(0.866cm,0.5cm)},z={(0cm,\Zscale cm)}]

% Defining hsb color to have a color scale
\colorlet{redhsb}[hsb]{red}     %
\colorlet{bluehsb}[hsb]{blue}   %

% Drawing the system of axes
\draw[->] (0,0,0) -- (1,0,0) node [black,left] {x};
\draw[->] (0,0,0) -- (0,1,0) node [black,left] {y};
\draw[->] (0,0,0) -- (0,0,1/\Zscale) node [black,left] {z};

% Write unit on x and y
\foreach \p in {1,...,\maxX}{
\draw {(\p,0,0)} node[right] {\p};
% Draw the grid
\foreach \q in {1,...,\maxY}{
\draw[black] (\p-0.5,\q-0.5,0) -- (\p+0.5,\q-0.5,0) -- (\p+0.5,\q+0.5,0) -- (\p-0.5,\q+0.5,0) -- (\p-0.5,\q-0.5,0);
}
}
\foreach \p in {1,...,\maxY}{
\draw {(\maxX+1,\p,0)} node[left] {\p};
}

\foreach \p in {1,...,\rows}{
\pgfplotstablegetelem{\p}{[index] 0}\of{\firsttable}    % The order in which the bars are drawn is determined by
\let\x\pgfplotsretval                                   %    the order of the lines in the data file.
\pgfplotstablegetelem{\p}{[index] 1}\of{\firsttable}    % And as the drawings just pile up, the last one just goes
\let\y\pgfplotsretval                                   %    on top of the previous drawings.
\pgfplotstablegetelem{\p}{[index] 2}\of{\firsttable}    % The order here works with chosen view angle, if you
\let\z\pgfplotsretval                                   %    change the angle, you might have to change it.

\pgfmathsetmacro{\w}{0.8/2} % half the width of the bars

\pgfmathtruncatemacro{\teinte}{100-((\z/\maxZ)*100)}
\colorlet{col}[rgb]{bluehsb!\teinte!redhsb}
% Unseen faces from orginal view, but if you change the angle ....
%\fill[col] (\x-\w,\y-\w,\z) -- (\x-\w,\y+\w,\z) -- (\x-\w,\y+\w,0) -- (\x-\w,\y-\w,0) -- (\x-\w,\y-\w,\z);
%   \draw[black] (\x-\w,\y-\w,\z) -- (\x-\w,\y+\w,\z) -- (\x-\w,\y+\w,0) -- (\x-\w,\y-\w,0) -- (\x-\w,\y-\w,\z);
%\fill[col] (\x-\w,\y+\w,\z) -- (\x+\w,\y+\w,\z) -- (\x+\w,\y+\w,0) -- (\x-\w,\y+\w,0) -- (\x-\w,\y+\w,\z);
%   \draw[black](\x-\w,\y+\w,\z) -- (\x+\w,\y+\w,\z) -- (\x+\w,\y+\w,0) -- (\x-\w,\y+\w,0) -- (\x-\w,\y+\w,\z);
% Visible faces from original view
\fill[col] (\x+\w,\y+\w,\z) -- (\x+\w,\y-\w,\z) -- (\x+\w,\y-\w,0) -- (\x+\w,\y+\w,0) -- (\x+\w,\y+\w,\z);
\draw[black](\x+\w,\y+\w,\z) -- (\x+\w,\y-\w,\z) -- (\x+\w,\y-\w,0) -- (\x+\w,\y+\w,0) -- (\x+\w,\y+\w,\z);
\fill[col!60!gray] (\x+\w,\y-\w,\z) -- (\x-\w,\y-\w,\z) -- (\x-\w,\y-\w,0) -- (\x+\w,\y-\w,0) -- (\x+\w,\y-\w,\z);
\draw[black](\x+\w,\y-\w,\z) -- (\x-\w,\y-\w,\z) -- (\x-\w,\y-\w,0) -- (\x+\w,\y-\w,0) -- (\x+\w,\y-\w,\z);
% Top face
\fill[top color=col!40!gray, bottom color=col!80!gray] (\x-\w,\y-\w,\z) -- (\x-\w,\y+\w,\z) -- (\x+\w,\y+\w,\z) -- (\x+\w,\y-\w,\z) -- (\x-\w,\y-\w,\z) ;
\draw[black] (\x-\w,\y-\w,\z) -- (\x-\w,\y+\w,\z) -- (\x+\w,\y+\w,\z) -- (\x+\w,\y-\w,\z) -- (\x-\w,\y-\w,\z);
}

\end{tikzpicture}

\end{document}


Which gives the image :

As you can see I added some features which are detailed in the comments of the code.

I hope it can help someone, thanks for reading.

To complete this, here is the Matlab code I used to generate the data file from the data in the matrix MAC.

fileID = fopen('DataOutMac.dat','w');
MaxMAC = max(MAC(:));

fprintf(fileID,'X \t\t Y \t\t Z \n');
%Maximums
fprintf(fileID,['' num2str(size(MAC,1)) ' \t\t ' num2str(size(MAC,2)) ' \t\t ' num2str(MaxMAC) ' \t\t %% max \n \n']);
%All the values
for i=1:size(MAC,1)
for j=size(MAC,2):-1:1
if MAC(i,j)>(MaxMAC/10000)  % To remove the smallest bars
fprintf(fileID,['' num2str(i) ' \t\t ' num2str(j) ' \t\t%12.8f \n'], MAC(i,j));%'%12.8f\n'], MAC(i,j));
end
end
end
fclose(fileID);