DEV Community

Cover image for 8 Python chart examples using Matplotlib
Onelinerhub
Onelinerhub

Posted on

8 Python chart examples using Matplotlib

1. 3D Scatter chart

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(projection='3d')

ax.scatter(1, 1, 1)
ax.scatter(2, 2, 1)
ax.scatter(2, 3, 0)

plt.show()
Enter fullscreen mode Exit fullscreen mode

Where projection='3d' is used to set 3d mode for this chart, .scatter( plots a point chart.

Open original or edit on Github.

2. Table

Well, this is not a chart, but tables are still used sometimes.

import matplotlib.pyplot as plt

data = [[1, 2, 3, 4, 5],
        [10,20,30,40,50],
        [11,21,31,41,51]]

plt.table(data, loc='center', colLabels=['A','B','C','D','E'])

plt.show()
Enter fullscreen mode Exit fullscreen mode

Here data is the data to use for table cells. Then we call .table( to plot a table and colLabels to define column titles.

Open original or edit on Github.

3. Boxplot chart

import matplotlib.pyplot as plt

plt.boxplot([2,3,6,2,4,5,1,10])

plt.show()
Enter fullscreen mode Exit fullscreen mode

We just use .boxplot( to plot boxplot chart.

Open original or edit on Github.

4. Line chart

import matplotlib.pyplot as plt
plt.plot([1,2,10,6,15,3,4])
plt.show()
Enter fullscreen mode Exit fullscreen mode

The .plot( is used to plot a line based on given data.

Open original or edit on Github.

5. Bar chart

import matplotlib.pyplot as plt
plt.bar(['UA', 'UK', 'USA'], [10, 11, 12])
plt.show()
Enter fullscreen mode Exit fullscreen mode

The .bar method will plot bar chart, while ['UA', 'UK', 'USA'] is used as x-axis values and [10, 11, 12] as y-axis values.

Open original or edit on Github.

6. Heatmap

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
im = ax.imshow([[0.8, 2.4, 2.5], [1.3, 1.2, 0.0], [0.1, 2.0, 0.0]])

plt.show()
Enter fullscreen mode Exit fullscreen mode

To draw heatmap we use .imshow(, which displays given data as an image.

Open original or edit on Github.

7. Histogram

import matplotlib.pyplot as plt

x = [1,2,5,1,2,3,5,6,7,4,2,2,4,5,6]
plt.hist(x,bins=5)
plt.show()
Enter fullscreen mode Exit fullscreen mode

To build a histogram we use .hist( and set bins - number of histogram bins (bars) to group data into.

Open original or edit on Github.

8. World map

import matplotlib.pyplot as plt
import geopandas

world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
world.plot()
plt.show()
Enter fullscreen mode Exit fullscreen mode

First, we load geopandas - module to work with maps and geo charts. Then world.plot()` can be used to plot world map.

Open original or edit on Github.

Top comments (0)