Public id: Python Programming time
Visual charts, there are quite a variety of, but common also on the following several, other more complex, mostly also based on the following several combinations, transformation. For starters, it’s easy to be overwhelmed by the sheer number of chart types on the site, which can cause confusion among different chart rendering methods.
So here, I’ve compiled six common basic chart types that you can learn from by comparison.
01. Line charts
If you draw a line graph, if you don’t have a lot of data, the graph will be zigzagging, but once you have a large data set, like our example below, with 100 points, what we see with the naked eye will be a smooth curve.
Here I draw three lines, and plt.plot is done three times.
import numpy as np
import matplotlib.pyplot as plt
x= np.linspace(0.2.100)
plt.plot(x, x, label='linear')
plt.plot(x, x**2, label='quadratic')
plt.plot(x, x**3, label='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Simple Plot")
plt.legend()
plt.show()
Copy the code
show image
02. Scatter plot
In fact, the scatter chart and line chart are the same principle, the scatter chart points connected with lines is a line chart. So to draw a scatter plot, just set up a line.
Note: I’m also drawing three lines here, but unlike above, I’m using only one plt.plot.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0..5..0.2)
# red dash, blue square, green triangle
plt.plot(x, x, 'r--', x, x**2.'bs', x, x**3.'g^')
plt.show()
Copy the code
show image
03. Histogram
Histograms, you’re familiar with them. Here Xiao Ming makes it harder by drawing two frequency histograms in one diagram. This should also be encountered in the actual scene, because it is really convenient to compare, right?
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(19680801)
mu1, sigma1 = 100.15
mu2, sigma2 = 80.15
x1 = mu1 + sigma1 * np.random.randn(10000)
x2 = mu2 + sigma2 * np.random.randn(10000)
# the histogram of the data
# 50: Divide the data into 50 groups
# facecolor: color; Alpha: Transparency
Density: is the density, not the specific value
n1, bins1, patches1 = plt.hist(x1, 50, density=True, facecolor='g', alpha=1)
n2, bins2, patches2 = plt.hist(x2, 50, density=True, facecolor='r', alpha=0.2)
# n: probability value; Bins: Specific values; Patches: A histogram object.
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(110.025..r'$\mu=100,\ \sigma=15$')
plt.text(50.025..r'$\mu=80,\ \sigma=15$')
# set the specific range of the x and y axes
plt.axis([40.160.0.0.03])
plt.grid(True)
plt.show()
Copy the code
show image
4. A histogram
Similarly, I’m not going to draw simple bar charts, but I’m going to draw three more difficult ones.
4.1 Parallel bar chart
import numpy as np
import matplotlib.pyplot as plt
size = 5
a = np.random.random(size)
b = np.random.random(size)
c = np.random.random(size)
x = np.arange(size)
How many types are there? Just change n
total_width, n = 0.8.3
width = total_width / n
# Redraw the coordinates of x
x = x - (total_width - width) / 2
# offset is used here
plt.bar(x, a, width=width, label='a')
plt.bar(x + width, b, width=width, label='b')
plt.bar(x + 2 * width, c, width=width, label='c')
plt.legend()
plt.show()
Copy the code
show image
4.2 Superimposed bar chart
import numpy as np
import matplotlib.pyplot as plt
size = 5
a = np.random.random(size)
b = np.random.random(size)
c = np.random.random(size)
x = np.arange(size)
# offset is used here
plt.bar(x, a, width=0.5, label='a',fc='r')
plt.bar(x, b, bottom=a, width=0.5, label='b', fc='g')
plt.bar(x, c, bottom=a+b, width=0.5, label='c', fc='b')
plt.ylim(0.2.5)
plt.legend()
plt.grid(True)
plt.show()
Copy the code
show image
05. The pie chart
5.1 Ordinary pie Chart
import matplotlib.pyplot as plt
labels = 'Frogs'.'Hogs'.'Dogs'.'Logs'
sizes = [15.30.45.10]
# Set the separation distance, 0 means no separation
explode = (0.0.1.0.0)
plt.pie(sizes, explode=explode, labels=labels, autopct='% 1.1 f % %',
shadow=True, startangle=90)
# Equal Aspect Ratio ensures that the graph is perfectly round
plt.axis('equal')
plt.show()
Copy the code
show image
5.2 Nested pie charts
import numpy as np
import matplotlib.pyplot as plt
Set the width of each ring
size = 0.3
vals = np.array([[60..32.], [37..40.], [29..10.]])
# Get_cmap to get random colors
cmap = plt.get_cmap("tab20c")
outer_colors = cmap(np.arange(3) *4)
inner_colors = cmap(np.array([1.2.5.6.9.10]))
print(vals.sum(axis=1))
# / 92. 77. 39.
plt.pie(vals.sum(axis=1), radius=1, colors=outer_colors,
wedgeprops=dict(width=size, edgecolor='w'))
print(vals.flatten())
# [60.32.37.40.29.10]
plt.pie(vals.flatten(), radius=1-size, colors=inner_colors,
wedgeprops=dict(width=size, edgecolor='w'))
# equal makes a perfect circle
plt.axis('equal')
plt.show()
Copy the code
show image
5.3 Polar pie chart
Say cool, pole axis pie chart is also one of the best, here must also learn.
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(19680801)
N = 10
theta = np.linspace(0.0.2 * np.pi, N, endpoint=False)
radii = 10 * np.random.rand(N)
width = np.pi / 4 * np.random.rand(N)
ax = plt.subplot(111, projection='polar')
bars = ax.bar(theta, radii, width=width, bottom=0.0)
# left means where to start,
# radii represents the length (radius) drawn from the center point to the edge
# width indicates the arc length at the end
# Customize colors and opacity
for r, bar in zip(radii, bars):
bar.set_facecolor(plt.cm.viridis(r / 10.))
bar.set_alpha(0.5)
plt.show()
Copy the code
show image
6. 3 d figure
6.1 Drawing a THREE-DIMENSIONAL scatter diagram
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
data = np.random.randint(0.255, size=[40.40.40])
x, y, z = data[0], data[1], data[2]
ax = plt.subplot(111, projection='3d') # Create a 3d drawing project
# Divide the data points into three parts and draw them in different colors
ax.scatter(x[:10], y[:10], z[:10], c='y') Draw data points
ax.scatter(x[10:20], y[10:20], z[10:20], c='r')
ax.scatter(x[30:40], y[30:40], z[30:40], c='g')
ax.set_zlabel('Z') # axis
ax.set_ylabel('Y')
ax.set_xlabel('X')
plt.show()
Copy the code
show image
6.2 Draw a three-dimensional plan
from matplotlib import pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
X = np.arange(4 -.4.0.25)
Y = np.arange(4 -.4.0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
Help (ax.plot_surface) = help(ax.plot_surface)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='rainbow')
plt.show()
Copy the code
show image