简体   繁体   中英

dash from the point to x and y axes in matplotlib

在此处输入图片说明

as you can see, I want to make the dash connect to the x and y axes. There is always a small gap.

I use matplotlib the vline function, and I don't know how to use the transform parameters.

Using vlines and hlines from matplotlib.pyplot , you can specify your axes and your line limits:

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()

在此处输入图片说明

Here is a solution using plt.plot to draw the lines.

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)

在此处输入图片说明

enter image description here The result is beautiful, but the code not so good.

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() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM