2D Charts

Learn to create various 2D charts in Python with the knowledge of MATLAB.

We'll cover the following...

2D charts are graphical representations of data that use a 2D plane to display information. We are going to create some common 2D charts in MATLAB and Python.

The bar chart

As the name implies, a bar chart is a graph that uses bars to represent different categories of data. The length of each bar represents the value of that category. Bars can be vertical or horizontal.

The bar chart
The bar chart

For the vertical bar charts, we use the bar() function in MATLAB. Let’s see the implementation of the bar() function.

C++
index = 1:5;
values = [6,2,7,3,8];
f = figure();
bar(index,values,'FaceColor',[.42 .37 .73])
xticklabels({'A','B','C','D','E'})
legend('First')
title('A Bar Chart',"fontsize", 16,'Color','r');
ylim([0 10])
xlabel('Category')
ylabel('Bar Value')
  • Line 1: We initialize the index array with x-axis values.

  • Line 2: We initialize the values array with y-axis values.

  • Line 4: Using the bar() function, we plot a bar chart using four arguments:

    • The first argument is the x-axis values.

    • The second argument is the y-axis values.

    • The third argument specifies which property we are going to set. In this case, it is FaceColor.

    • The fourth argument is the value of color. In this case, we use the RGB percentage value of [.42 .37 .73].

  • Line 5: We use the xticklabel() command to specify labels on the x-axis with respect to each index (x-axis) value. It will be enclosed in curly brackets {} and separated by a comma ,.

  • Line 6: We create a legend using the legend() function to categorize different types of data.

  • Line 7: We set a figure title using the title() function. It has five arguments:

    • The first argument is the title of the figure. It will be written as a string.

    • The second and fourth arguments define a property. Here, we have fontsize and color to set the font size and color of the title.

    • The third and fifth arguments represent the value of the property. Here, we have fontsize equal to 16 and color equal to r means red.

  • Line 8: We use ylim command to set the upper and lower limits of the y-axis. The first argument is the lower limit, followed by an upper limit.

In Python, we use plt.bar() function from the Matplolib library to plot a bar chart.

Python 3.10.4
import matplotlib.pyplot as plt
import numpy as np
index = np.arange(1,6)
values = np.array([6,2,7,3,8])
plt.figure(dpi=300)
plt.bar(index,values,color = (.42, .37, .73))
plt.xticks(index,['A','B','C','D','E'])
plt.legend(['First'])
plt.title('A Bar Chart',fontsize=16,color = 'red')
plt.ylim(0,10)
plt.xlabel('Category')
plt.ylabel('Bar Value')
  • Line 3: We initialize an numpy.ndarray object index with values 1 to 5 with step of 1.

  • Line 4: We initialize a numpy array values with y-axis values.

  • Line 6: ...