python 画图-标注点,画虚线

本文展示如何利用Python的Matplotlib库和NumPy库绘制二次函数的图像,并通过散点和文本标注的方式突出函数的最小值点。同时,通过调整坐标轴的位置使图表更直观。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载

import matplotlib.pyplot as plt
import numpy as np

# 函数图
x = np.arange(0, 3, 0.01)
y = x ** 2 - 3 * x + 2
plt.plot(x, y)
plt.scatter([1.5],[-0.25],s=25,c='r') # 标注最小值
# 点的标签(座标中加减的 `0.15` 是显示位置的偏移,避免挡住点)
plt.text(1.5+0.15, -0.25-0.15, 'minima', ha='center', va='bottom', fontsize=10.5)  # horizontal alignment

# 画两条虚线
plt.plot([0, 1.5], [-0.25, -0.25], c='b', linestyle='--')
plt.plot([1.5, 1.5], [0, -0.25], c='b', linestyle='--')

# 座标轴调位
ax = plt.gca()
# 移到原点
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))

在这里插入图片描述

<think>我们正在讨论如何使用Python的matplotlib库设置线型样式。根据引用[3]和引用[4],我们可以设置线型(linestyle)来改变线条的外观。线型可以通过几种方式指定:1.使用字符串缩写:例如,实线为'-',虚线为'--',划线为'-.',线为':'。2.使用参数名:在plot函数中,我们可以通过`linestyle`(或简写`ls`)参数来指定。引用[4]中给出了线型符号的对应关系:'-'实线'--'短线(虚线)'-.'短相间线(划线)':'虚线(线)另外,在引用[1]的示例中,我们看到了两种设置线型的方法:方法1:使用格式字符串,将颜色、标记和线型组合在一起。例如:'ro--'表示红色圆圈标记和虚线。方法2:分别使用关键字参数:color='r',linestyle='dashed',marker='o'因此,我们可以通过这两种方式来设置线型。下面我们通过示例代码来展示如何设置不同的线型:</think>在 Python 的 Matplotlib 库中,设置线型样式主要通过 `linestyle` 参数(或其简写 `ls`)实现。以下是详细方法和示例: ### 一、设置线型的 4 种方法 1. **字符串简写**(最常用): ```python plt.plot(x, y, '--') # 虚线 ``` 常用简写对照: - `'-'` 或 `'solid'`:实线(默认) - `'--'` 或 `'dashed'`:虚线 - `'-.'` 或 `'dashdot'`:划线 - `':'` 或 `'dotted'`:线 2. **明确参数命名**: ```python plt.plot(x, y, linestyle='dotted') # 线 ``` 3. **格式字符串组合**(颜色+标记+线型): ```python plt.plot(x, y, 'r*:') # 红色星号标记 + 线 ``` 4. **设置样式表**(全局生效): ```python plt.style.use('seaborn-whitegrid') # 使用预设样式库[^5] ``` ### 二、完整示例代码 ```python import matplotlib.pyplot as plt import numpy as np # 创建数据 x = np.linspace(0, 10, 100) y = np.sin(x) # 设置不同线型绘图 plt.figure(figsize=(10, 6)) # 设置布大小[^3] plt.plot(x, y, ls='-', label='实线 (solid)') # 方法1 plt.plot(x, y+0.5, '--', label='虚线 (dashed)') # 方法2 plt.plot(x, y+1.0, linestyle='-.', label='划线') # 方法3 plt.plot(x, y+1.5, 'g:', label='线 (dotted)') # 方法4组合样式 # 添加标注 plt.title('Matplotlib 线型样式演示', fontsize=14) plt.xlabel('X 轴', fontsize=12) plt.ylabel('Y 轴', fontsize=12) plt.legend(loc='best') # 自动选择图例位置[^2] plt.grid(ls=':', alpha=0.5) # 设置网格为半透明线 plt.show() ``` ### 三、线型效果说明 | 线型代码 | 样式示例 | 说明 | |----------|----------------|-------------------| | `'-'` | ———————— | 实线 (默认) | | `'--'` | - - - - - - - | 虚线 | | `'-.'` | _._._._._._._ | 划线 | | `':'` | .............. | 线 | > 提示:可通过 `linewidth` 参数调整线宽(如 `lw=2.5`),通过 `alpha` 调整透明度(如 `alpha=0.7`)[^4]。 ### 四、自定义虚线样式 使用元组指定复杂模式: ```python # 格式: (偏移量, (线段长度, 间隙长度, 线段长度, ...)) plt.plot(x, y, ls=(0, (5, 2, 1, 2)), label='自定义虚线') ``` 表示:5pt线段 → 2pt间隙 → 1pt线段 → 2pt间隙(重复)[^3]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值