导入依赖

import matplotlib.pyplot as plt 
# Ignore warnings
import warnings
warnings.filterwarnings('ignore')

Line chart

x_data = np.linspace(0, 5, 100)  # Sample data
y_data = x_data**2
plt.plot(x_data,y_data)
plt.ylabel('responding variable')
plt.xlabel('independent variable')
plt.show()

Bar chart

fig, ax = plt.subplots() #to plot on same axes

students = ['Alex', 'Jake', 'Brenda', 'Liz']
height = [175, 190, 165, 158]
bar_labels = ['red', 'blue', 'pink', 'green']
bar_colors = ['tab:red', 'tab:blue', 'tab:pink', 'tab:green']

ax.bar(students, height, label=bar_labels, color=bar_colors)

ax.set_ylabel('Height (cm)')
ax.set_title("Students' height and their favourite colour")
ax.legend(title='Colour')

plt.show()

Pie chart

students = ['Alex', 'Jake', 'Brenda', 'Liz']
donation = [100,50,60,120]

fig, ax = plt.subplots()
ax.pie(donation, labels=students)
ax.set_title("Contribution of students in a fundraising")

#Export figure as png
plt.savefig('pie.png', bbox_inches='tight')

marker and linestyle

matplotlib 中,marker 参数用于指定图表上数据点的标记样式。'o' 是一个圆圈标记,用于在图表的每个数据点位置绘制一个小圆圈。除了圆圈外,还有许多其他类型的标记可供选择。

下面是一些常用的 matplotlib 标记类型:

  • '.': 点
  • 'o': 圆圈
  • 's': 正方形
  • '^': 向上的三角形
  • '>': 向右的三角形
  • '<': 向左的三角形
  • 'v': 向下的三角形
  • 'p': 五角星
  • '*': 星号
  • '+': 加号
  • 'x': 叉号
  • 'D': 菱形
  • 'H': 六边形1
  • '8': 六边形2

您可以在 plot 函数中使用 marker 参数来指定这些标记中的任何一个,例如:

plt.plot(x, y, marker='*', linestyle='-')

这将在图表的每个数据点上绘制一个星号。选择哪种标记类型通常取决于您的个人喜好,以及哪种标记能在您的图表中提供最好的可视化效果。

matplotlib 中,linestyle 参数用来定义线条的样式。这对于区分图表中的不同数据系列或改善图表的可读性非常有用。以下是一些可用的 linestyle 选项:

  • '-''solid': 实线
  • '--''dashed': 虚线
  • '-.''dashdot': 点划线
  • ':''dotted': 点线
  • '''None': 不画线

您可以根据需要选择其中的任何一个样式来自定义您的折线图。例如:

plt.plot(x, y, linestyle='--')  # 会绘制虚线