1

在此处输入图像描述

如您所见,我想让破折号连接到 x 和 y 轴。总是有一个小的差距。

我用matplotlib 的是vline函数,不知道怎么用transform参数。

4

3 回答 3

1

使用vlinesand hlinesfrom matplotlib.pyplot,您可以指定轴和线限制:

from matplotlib import pyplot as plt

# Drawing example diagram

plt.scatter(x=11,y=0.891)
plt.xlim(5,20)
plt.xticks([5,8,11,14,17,20])
plt.ylim(0.780,0.9)

# Specifying lines, notice how despite setting xmin and ymin lower than your axes, 
# the lines stop at each boundary

plt.vlines(x=11, ymin=0.7, ymax=0.891, colors='r',linestyles='dashed')
plt.hlines(y=0.891, xmin=4, xmax=11, colors='k',linestyles='dashed')

plt.show()

在此处输入图像描述

于 2020-03-13T15:35:17.417 回答
0

这是plt.plot用于绘制线条的解决方案。

import matplotlib.pyplot as plt
import numpy as np

y = np.random.randint(1, 10, 10)
x = np.arange(len(y))

point = [x[2], y[2]]

plt.plot(x,y)

plt.plot((point[0], point[0]), (0, point[1]), '--')
plt.plot((0, point[0]), (point[1], point[1]), '--')

plt.xlim(0,10)
plt.ylim(0,10)

在此处输入图像描述

于 2020-03-14T08:40:33.653 回答
0

在此处输入图像描述 结果很漂亮,但代码不太好。

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker as ticker


x = [i for i in range(5, 21, 3)]
# [5, 8, 11, 14, 17, 20]
y = [0.780, 0.865, 0.891, 0.875, 0.884, 0.870]

y_max_index = np.argmax(y)
# print(y_max_index)

# get the max point
x_max = x[y_max_index]
y_max = y[y_max_index]

fig, ax = plt.subplots()

ax.plot(x, y, marker='o', color='r')

# set x ticks as [5, 8, 11, 14, 17, 20]
my_x_ticks = x
plt.xticks(my_x_ticks)

# set x and y lim
axe_y_min, axe_y_max = ax.get_ylim()
axe_x_min, axe_x_max = ax.get_xlim()

ax.set_ylim(axe_y_min, axe_y_max)
ax.set_xlim(axe_x_min, axe_x_max)
plt.gca().yaxis.set_major_formatter(ticker.FormatStrFormatter('%.3f'))      # set y axe format

anno_text = "(11,  0.891)"
plt.annotate(anno_text, xy=(x_max, y_max), xytext=(x_max+0.5, y_max))  # annotate

y_scale_trans = (y_max - axe_y_min) / (axe_y_max - axe_y_min)
x_scale_trans = (x_max - axe_x_min) / (axe_x_max - axe_x_min)

ax.vlines(x_max, 0, y_scale_trans, transform=ax.get_xaxis_transform(), colors='black', linestyles="dashed")
ax.hlines(y_max, 0, x_scale_trans, transform=ax.get_yaxis_transform(), colors='black', linestyles="dashed")
plt.ylabel("准确率")
plt.xlabel("滑动窗口大小")

plt.savefig("滑动窗口.pdf", dpi=100)
plt.show() 
于 2020-03-14T14:52:36.740 回答