You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

绘制主图副图时,如何实现弧形连接线的绘制?

如何在绘图中优雅添加右上角弧形线条

下面针对两种常用绘图工具给出代码实现方案,无需依赖外部图片编辑工具:

Python (Matplotlib)

利用Matplotlib的patches.Arc可以直接在图中绘制弧形,步骤如下:

  1. 先绘制主图/副图的内容
  2. 获取坐标轴的边界范围,计算弧形的位置参数
  3. 创建Arc对象并添加到坐标轴上

示例代码:

import matplotlib.pyplot as plt
from matplotlib.patches import Arc

# 1. 绘制主图示例数据
fig, ax = plt.subplots(figsize=(8, 5))
x = [1,2,3,4,5]
y = [2,4,3,5,4]
ax.plot(x, y, marker='o', label='主图数据')

# 2. 计算弧形参数(以右上角区域为例)
x_center = 4.5  # 弧形圆心x坐标
y_center = 4.8  # 弧形圆心y坐标
radius = 0.6    # 弧形半径
# 设置弧形的起始角度和终止角度(对应右上角的弧形,比如从180度到270度)
arc = Arc((x_center, y_center), width=2*radius, height=2*radius,
          angle=0, theta1=180, theta2=270, color='red', linewidth=2)

# 3. 添加弧形到坐标轴
ax.add_patch(arc)

ax.legend()
plt.show()

你可以根据实际图的坐标范围,调整x_centery_centerradius以及theta1/theta2的数值,来匹配需要的弧形位置和弧度。

R (ggplot2)

如果使用ggplot2,可以借助ggforce包的geom_arc函数,或者直接用geom_curve绘制近似弧形:

方法1:使用ggforce的geom_arc

library(ggplot2)
library(ggforce)

# 绘制主图示例数据
p <- ggplot(data.frame(x = 1:5, y = c(2,4,3,5,4)), aes(x, y)) +
  geom_line(marker = 'o') +
  geom_point()

# 添加右上角弧形
p + geom_arc(aes(x0 = 4.5, y0 = 4.8, r = 0.6, start = pi, end = 3*pi/2),
             color = 'red', size = 2, inherit.aes = FALSE)

参数说明:x0/y0是圆心坐标,r是半径,startend用弧度表示起始/终止角度(pi对应180度,3*pi/2对应270度)。

方法2:使用geom_curve绘制平滑弧形

如果不想额外安装包,也可以用geom_curve

ggplot(data.frame(x = 1:5, y = c(2,4,3,5,4)), aes(x, y)) +
  geom_line(marker = 'o') +
  geom_point() +
  geom_curve(aes(x = 4, y = 5, xend = 5, yend = 4),
             color = 'red', size = 2, curvature = -0.5)

调整curvature参数可以改变弧形的弯曲程度,负数对应向左上方弯曲。

内容的提问来源于stack exchange,提问作者Breeze

火山引擎 最新活动