Graph point on straight line (number line) in Python

旧巷老猫 提交于 2020-01-12 07:47:05

问题


Trying to figure out what's the best way to graph a point on a number line in python. Essentially trying to make something similar to the image below:

I've been trying to use Matplotlib to do this but can't seem to figure it out. Anyone know of a package or anything out there I can use?


回答1:


I don't know of a specific package for this but you could do something like this in Matplotlib using hlines, vlines and plot.

import matplotlib.pyplot as plt

# set up the figure
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim(0,10)
ax.set_ylim(0,10)

# draw lines
xmin = 1
xmax = 9
y = 5
height = 1

plt.hlines(y, xmin, xmax)
plt.vlines(xmin, y - height / 2., y + height / 2.)
plt.vlines(xmax, y - height / 2., y + height / 2.)

# draw a point on the line
px = 4
plt.plot(px,y, 'ro', ms = 15, mfc = 'r')

# add an arrow
plt.annotate('Price five days ago', (px,y), xytext = (px - 1, y + 1), 
              arrowprops=dict(facecolor='black', shrink=0.1), 
              horizontalalignment='right')

# add numbers
plt.text(xmin - 0.1, y, '80', horizontalalignment='right')
plt.text(xmax + 0.1, y, '115', horizontalalignment='left')

plt.axis('off')
plt.show()




回答2:


Here ya go, official example from matplotlib, including example code and everything. To plot a labeled point on the line, just do a normal scatterplot with the y coordinates being 0:

https://matplotlib.org/examples/ticks_and_spines/tick-locators.html



来源:https://stackoverflow.com/questions/23186804/graph-point-on-straight-line-number-line-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!