Matplotlib - 3D Bar Plots



A 3D bar graph is a way to visually represent data in three dimensions, like height, width, and depth. You might have seen regular bar graphs, where bars are used to represent data values along one or two axes. In a 3D bar graph, however, the bars also have depth, giving a full representation of the data.

In a 3D bar graph, data is plotted along three axes: the x-axis, y-axis, and the z-axis. The x-axis represents the categories, the y-axis represents the subcategories and the z-axis represents the values for each category and subcategory −

3D Bar Graphs

3D Bar Graphs in Matplotlib

3D bar graph in Matplotlib is a visual representations of columns in three-dimensions (2D columns with depth). To create 3D bar graphs, we use the bar3d() function in the "mpl_toolkits.mplot3d" module. This function takes X, Y, and Z coordinates as arrays to plot the position of each bar in the three-dimensional space.

Let us start by drawing basic 3D bar graph.

Basic 3D Bar Graph

A basic 3D bar graph in Matplotlib is a representation of data using rectangular bars in a three-dimensional space. The position of each bar is defined along X, Y, and Z axes. The X axis defines the category, the Y axis defines the subcategory and the Z axis defines the values associated with each subcategory.

Example

In this example, we are drawing basic 3D bar graphs. We first create a sample data, where the category is the vehicle type ('Car') and the subcategory is the sales region ('North', 'South'). The result is a 3D bar graph where the height of the bars represents the total sales volume of each vehicle type in each region −

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Sample data
vehicle_type = ['Car']
sales_region = ['North', 'South']
sales_volume = [[150, 120]]

# Creating a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plotting 3D bars
for i in range(len(vehicle_type)):
    for j in range(len(sales_region)):
        ax.bar3d(i, j, 0, 0.8, 0.8, sales_volume[i][j])

ax.set_xlabel('Vehicle Type')
ax.set_ylabel('Sales Region')
ax.set_zlabel('Sales Volume')
ax.set_title('Basic 3D Bar Graph')

# Displaying the plot
plt.show()

Output

Following is the output of the above code −

Basic 3D Bar Graphs

Stacked 3D Bar Graphs

A stacked 3D bar graph in Matplotlib is combining multiple 3D bar graphs on top of each other. Each bar gives the contribution of a single category and subcategory, and when stacked with other graphs it helps us to see the contribution made by the individual categories and subcategories to a total value in a three-dimensional space.

Example

The following example creates a stacked 3D graph, which allows us to see the total investment amount made for each investment category ('Equity', 'Mutual Fund', 'Gold') for each month ('January','February','March'). In the resultant plot, the individual bars represent contributions of each investment category while the stacked 3D bars gives the total invesment amount in each category −

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Sample data
months = ['January', 'February', 'March']
investment_categories = ['Equity', 'Mutual Funds', 'Gold']
investment_amount = [[1000, 2000, 1500],[1800, 1600, 1200],[2100, 1700, 2500]]

# Creating a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plotting stacked 3D bars
for i in range(len(months)):
    bottom = 0
    for j in range(len(investment_categories)):
        ax.bar3d(i, j, bottom, 0.8, 0.8, investment_amount[i][j], shade=True)
        bottom += investment_amount[i][j]

ax.set_xlabel('Months')
ax.set_ylabel('Investment Categories')
ax.set_zlabel('Investment Amount')
ax.set_title('Stacked 3D Bar Graph')

# Displaying the plot
plt.show()

Output

Output of the above code is as follows −

Stacked 3D Bar Graphs

Grouped 3D Bar Graphs

In Matplotlib, a grouped 3D bar graph creates a comparison between multiple groups across different categories. Each bar has a distinct value on the X, Y, and Z axes and represents a distinct category. A group is formed by combining the distinct bars of each category or subcategory.

Example

In the following example, we are creating a grouped 3D bar graph for different products ('Ring', 'Bracelet', 'Necklace') across different regions ('West','East'). The graph is created by grouping the sales of each product over a time period. The resultant plot shows the regions, products and total sales on the x-axis, y-axis, and z-axis respectively −

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Sample data
product_regions = ['West', 'East']
products = ['Ring', 'Bracelet', 'Necklace']
sales_volume = [[[105, 125, 85],[92, 112, 85],[84, 95, 75]],[[123, 93, 103],[118, 95, 105],[85, 109, 119]]]

# Creating a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plotting grouped 3D bars
bar_width = 0.3
for i in range(len(product_regions)):
   for j in range(len(products)):
      x_position = i + j * bar_width
      ax.bar3d(x_position, range(len(products)), 0, bar_width, 0.8, sales_volume[i][j])

ax.set_xlabel('Product Regions')
ax.set_ylabel('Products')
ax.set_zlabel('Sales Volume')
ax.set_title('Grouped 3D Bar Graph')

# Displaying the plot
plt.show()

Output

After executing the above code, we get the following output −

Grouped 3D Bar Graphs

3D Bar Graphs with Custom Colors

In Matplotlib, we can customize the colors of bars in a 3D bar graph to improvise visual clarity. It is useful in situations where different categories need to be represented with different colors in a three dimensional space.

Example

Here, we are having a category of subjects ('Mathematics', 'Physics', 'Chemistry') and subcategory of students ('A', 'B', 'C'). To assign different colors, we create a tuple of colors and set this tuple to the "color" property in bar3d() function. In the final plot, the bar color of each student is different based on their performance −

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Sample data
subjects = ['Mathematics', 'Physics', 'Chemistry']
student_name = ['A', 'B', 'C']
marks = [[90, 95, 93],[75, 78, 70],[30, 25, 35]]

# Custom colors for each student based on marks
colors = {'A': 'green', 'B': 'yellow', 'C': 'red'}

# Creating a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Plotting 3D bars with custom colors
for i in range(len(subjects)):
   for j in range(len(student_name)):
      ax.bar3d(i, j, 0, 0.8, 0.8, marks[j][i], color=colors[student_name[j]])

ax.set_xlabel('Subjects')
ax.set_ylabel('Student Name')
ax.set_zlabel('Marks')
ax.set_title('3D Bar Graph with Custom Colors')

# Displaying the plot
plt.show()

Output

The output obtained is as shown below −

3D Bar Graphs with Custom Colors
Advertisements