相信有不少的小伙伴在学函数图像,我直接把代码奉上
from matplotlib import pyplot as plt
import matplotlib as mpl
from math import *
def draw_graph(functions, sampling_density = 2.0, show_legend = True, dot_size = 20, scatter_or_line_chart = "scatter", scatter_style = "b,o", line_chart_style = "b,o,--,t", x_label = "x->", y_label = "y->", phase_line = True, multicolor = ["nullptr"], multiple_overlapping_images = [1], legend_of_each = ["nullptr"]):
"""
:param functions: type = <list [function1, function2, ...]> For each function, given x, return y.
:param sampling_density: type = <int (>= 1)> The frequency of sampling, the higher the clarity.
:param show_legend: type = <bool True or False> Is the legend displayed.
:param dot_size: type = <int (>= 1)> The size of each point.
:param scatter_or_line_chart: <string "scatter" or "line_chart"> Draw a scatter or line chart.
:param scatter_style: <string a,b> When drawing a scatter plot, color a and shape b.
:param line_chart_style: <string a,b,c,d> When drawing a line chart, the color a, the shape of the point b, and the shape of the line c. When d=t, scatter points are displayed; otherwise, scatter points are not displayed.
:param x_label: type = <string> Identification of the x-axis.
:param y_label: type = <string> Identification of the y-axis.
:param phase_line: type = <bool True or False> Is the phase line displayed.
:param multicolor: type = <list [color1, color2, ...]> The color of each line or image, if used by default, please set it to ["nullptr"].
:param multiple_overlapping_images: type = <list [l1, l2, ...]> Stack li images within i charts on the ground.
:param legend_of_each: type = <list [legend1, legend2, ...]> The icon name for each icon, if not needed, please set it to ["nullptr"].
:return: Based on the above parameters, draw and display the image.
"""
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
data_of_subplot = {
1: [1, 1], 2: [1, 2],
3: [1, 3], 4: [2, 2],
5: [2, 3], 6: [2, 3],
7: [2, 4], 8: [2, 4],
9: [3, 3], 10: [2, 5]
}
start = -(100 / 10 ** (sampling_density - 1))
end = 100 / 10 ** (sampling_density - 1)
add = end / 100
function_pos = -1
sub_cnt_pos = 1
sub_cnt = len(multiple_overlapping_images)
plt.figure(figsize = (4 * data_of_subplot[sub_cnt][1], 4 * data_of_subplot[sub_cnt][0]))
for i in multiple_overlapping_images:
plt.subplot(data_of_subplot[sub_cnt][0], data_of_subplot[sub_cnt][1], sub_cnt_pos)
legends = []
for j in range(i):
x_coordinate = []
y_coordinate = []
function_pos += 1
x = start
if legend_of_each[0] == "nullptr":
legends.append('f' + str(function_pos + 1))
else:
legends.append('$' + legend_of_each[function_pos] + '$')
while (x <= end):
try:
y = functions[function_pos](x)
except ValueError:
x = 0 + add
continue
if y >= start and y <= end:
x_coordinate.append(x)
y_coordinate.append(y)
x += add
plt.xlim(start, end)
plt.ylim(start, end)
plt.xlabel(x_label)
plt.ylabel(y_label)
if scatter_or_line_chart == "scatter":
style = scatter_style.split(',')
if multicolor[0] == "nullptr":
plt.scatter(x_coordinate, y_coordinate, s = dot_size, c = style[0], marker = style[1])
else:
plt.scatter(x_coordinate, y_coordinate, s = dot_size, c = multicolor[function_pos], marker = style[1])
elif scatter_or_line_chart == "line_chart":
style = line_chart_style.split(",")
if multicolor[0] == "nullptr":
plt.plot(x_coordinate, y_coordinate, color = style[0], linestyle = style[2])
else:
plt.plot(x_coordinate, y_coordinate, color = multicolor[function_pos], linestyle = style[2])
if style[3] == 't':
if multicolor[0] == "nullptr":
plt.scatter(x_coordinate, y_coordinate, s = dot_size, c = style[0], marker = style[1])
else:
plt.scatter(x_coordinate, y_coordinate, s = dot_size, c = multicolor[function_pos], marker = style[1])
if phase_line:
plt.plot([0, 0], [-100, 100], color = 'gray', linewidth = 1, alpha = 0.5)
plt.plot([-100, 100], [0, 0], color = 'gray', linewidth = 1, alpha = 0.5)
if show_legend and scatter_or_line_chart == "line_chart":
plt.legend(legends, loc = 'upper right')
sub_cnt_pos += 1
plt.show()
def f1(x):
return x ** 2
def f2(x):
return sin(x)
def f3(x):
return cos(x)
def f4(x):
return tan(x)
def f5(x):
return x ** 2 / 2
def f6(x):
return -(x ** 2 / 2)
def f7(x):
return -(x ** 2 / 3)
def f8(x):
return (x ** 2 / 2)
def f9(x):
return log(x, 2)
def f10(x):
return x ** 3 - x ** 2
def f11(x):
return x ** 4 - x ** 3
def f12(x):
return x ** 2 * 2
def f13(x):
return -x
def f14(x):
return x
def f15(x):
return x * 5
draw_graph([f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13, f14, f15],
scatter_or_line_chart = "line_chart", multicolor = ['black', 'red', 'green', 'blue', 'pink', 'yellow', 'orange', 'blue', 'green', 'black', 'red', 'yellow', 'green', 'gray', 'blue'],
multiple_overlapping_images = [1, 3, 2, 2, 1, 2, 1, 2, 1],
legend_of_each = ['x^2', 'sin(x)', 'cos(x)', 'tan(x)', 'x^2/2', '-x^2/2', '-x^2/3', 'x^2/3', 'log(2,x)', 'x^3-x^2', 'x^4-x^3', '2x^2', '-x', 'x', '5x']
)