Tagged: 3D bar graph, Data science, Data visualization

- This topic has 0 replies, 1 voice, and was last updated 2 years, 5 months ago by Idowu.

- AuthorPosts
- February 18, 2020 at 1:56 am #86064Spectator@idowu
Previously, I wrote an article on how to make bar graphs with the

**matplotlib**library. It was stated in that article that**matplotlib**is used to make most of the 2D visualizations with Python, but this article is focused on 3D bar graphs.Making the right visualizations for the right data is a great way to assess the interrelationship that exists between its features. Thus, giving it the ability to communicate effectively to an end-user.

Depending on the type and structure of a data, 2D and 3D bar graphs have specific situations where they can be applied. However, don’t be tempted to make a visualization that will not address what it should address. Else, its purpose will be defeated.

Although, the 3D bar graph is a 3-dimensional way of viewing the bars. A unique feature of the 3D bar graph is you can plot more than 3-dimensions at a time. In addition to the fact that you can define the starting point, the height and width of the bars, you can also set the depth of the bars.

The 3D bar graph is useful when the aim is to view the three sides of a data set against a set of continuous values. Let’s assume you want to make a chart to show the relative behavior of two categorical variables against a continuous one. You can either decide to make a line plot or a bar graph. However, if you intend to plot bars only, then you should consider a 3D bar graph.

Instead of the two axes in a 2D bar graph, a 3D chart has 3 axes (X, Y, and Z), with additional depth dimensions (dx, dy, and dz). Thus, the making of a 3D bar graph revolves around setting positions for the three axes. Usually, for a real-world problem, the X- and Y- axes bear categorical features. You can also think of Z as the axis that now performs the function of the Y-axis in 2D plots.

For this tutorial, I will be making 3D bars from data that contains the mortality rate of 5 countries due to injuries over 7 years. However, you can simply make up the data set with Microsoft Excel. What we want to do is view each country relative to the years on X and Y-axes. We also want to see through the continuous values that represent them on the Z-axis.

We will be making use of the

**mpl_toolkits.mplot3d**library. Let’s break each process down:**Loading the libraries**"""Load the necessary libraries and view the data""" import numpy as np import pandas as pd import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D df=pd.read_excel(r'data3.xlsx') print(df)

To prevent

**value error**, we should consider removing the “year” column from our data. This is to prevent it from being plotted along with the other values:df.drop('years', axis=1, inplace=True)

To make things easier, we need to change the data frame into an array by simply using

**df.values**– this will allow us to manipulate the data set:df1=df.values print(df.isnull().sum()) """Print the array and the summary""" print(df1)

We’ll now define the columns and rows variables:

columns = ['Afghanistan', 'Bangladesh', 'Brazil', 'China', 'Nigeria',] rows = [ '2008', '2009', '2010', '2011', '2012', '2013', '2014'] fig = plt.figure(figsize=(8, 6)) ax = Axes3D(fig) lx = len(df1[0]) ly = len(df1[:,0])

After defining the figure size with the

**fig**variable, the**ax**was used to fit the**fig**into**Axes3D**. The array was then sliced, by declaring that the length of the X-axis should run across the first row (**len(df1[0])**) – this will make the X-axis inherit the values of the 5 columns in the data set. Also, the Y-axis was made to run through the length of the entire rows of the first column (**len(df1[:,0]**)) – this makes it inherit the length of the 7 rows.xpos = np.arange(0, lx, 1) ypos = np.arange(0, ly, 1) """Print the array""" xpos, ypos = np.meshgrid(xpos + 0.25, ypos + 0.25) """Setting x, y and z positions""" xpos = xpos.flatten() ypos = ypos.flatten() zpos = np.zeros(lx*ly) """Making the depths""" dx = 0.25*np.ones_like(zpos) dy = dx.copy() dz = df1.flatten()

In the snippet above, x-position (

**xpos**) and y-position (**ypos**) were defined. The**meshgrid**values were also set – this is just to manipulate distances between each bar, you can play around it by tweaking the numbers. The x and y positions were then flattened, while z-position (**zpos**) was made to hold the continuous representative values of both the x and y axes. We also made the other dimensions of the axes with**dx**,**dy**and**dz**(these are the depths).Once everything is in place, let’s see what our 3D bars look like:

ax.bar3d(xpos, ypos, zpos, dx, dy, dz) plt.show()

To make more sense of the bar graph, we can further beautify the bar graph by adding stuff like colors, title, and ticks:

colors = ['red', 'yellow', 'brown', 'cyan', 'green']*ly ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=colors) """Set the x and y ticks""" ax.w_xaxis.set_ticklabels(columns) ax.w_yaxis.set_ticklabels(rows) ax.set_xlabel('Countries') ax.set_ylabel('Over the years') ax.set_zlabel('Number of cases') plt.title('Mortality due to injuries', bbox={'facecolor':'red'}) plt.show()

## The Entire Code

# -*- coding: utf-8 -*- """Load the necessary libraries""" import numpy as np import pandas as pd import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D df=pd.read_excel(r'data3.xlsx') df.drop('years', axis=1, inplace=True) df1=df.values print(df.isnull().sum()) print(df1) columns = ['Afghanistan', 'Bangladesh', 'Brazil', 'China', 'Nigeria',] rows = [ 'pad', '2008', '2009', '2010', '2011', '2012', '2013', '2014'] fig = plt.figure(figsize=(8, 6)) ax = Axes3D(fig) lx = len(df1[0]) ly = len(df1[:,0]) xpos = np.arange(0, lx, 1) ypos = np.arange(0, ly, 1) xpos, ypos = np.meshgrid(xpos + 0.25, ypos + 0.25) xpos = xpos.flatten() ypos = ypos.flatten() zpos = np.zeros(lx*ly) dx = 0.25*np.ones_like(zpos) dy = dx.copy() dz = df1.flatten() colors = ['red', 'yellow', 'brown', 'cyan', 'green']*ly ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=colors) ax.w_xaxis.set_ticklabels(columns) ax.w_yaxis.set_ticklabels(rows) ax.set_xlabel('Countries') ax.set_ylabel('Over the years') ax.set_zlabel('Number of cases') plt.title('Mortality due to injuries', bbox={'facecolor':'red'}) plt.show()

- AuthorPosts

- You must be logged in to reply to this topic.