最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python 3.x - Plotting a chart of numberlines - Stack Overflow

programmeradmin3浏览0评论

I have a a list of lists of integers as in the sample below.

xs = [[5,7,9], [3,4,15,19]]
ys = list(range(len(xs)))  # so in this case ys = [0,1]

I need to plot a chart of lines with y-coord being each element in ys, and will have a tick at the x-coordinate for each element in the corresponding element in xs[].

How best to do it with matplotlib?

Thanks

I have a a list of lists of integers as in the sample below.

xs = [[5,7,9], [3,4,15,19]]
ys = list(range(len(xs)))  # so in this case ys = [0,1]

I need to plot a chart of lines with y-coord being each element in ys, and will have a tick at the x-coordinate for each element in the corresponding element in xs[].

How best to do it with matplotlib?

Thanks

Share Improve this question edited Feb 15 at 12:24 skywalker asked Feb 14 at 23:53 skywalkerskywalker 799 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 0

This is the way I resolved it.

    f = plt.figure()
    f.set_figwidth(20)
    f.set_figheight(8)
    for ndx in range(len(xs)):
        ys = [ndx] * len(lines[ndx])
        #plt.scatter(lines[ndx], ys, marker='+')    # this plots markers only
        plt.plot(lines[ndx], ys, marker='+')        # this plots lines with markers
    plt.show()

If you have many lines to draw, you can use LineCollection, which is quite efficient:

import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from itertools import repeat, chain

xs = [[5,7,9], [3,4,15,19]]

lines = [list(zip(x, repeat(i)))
         for i, x in enumerate(xs)]
# [[(5, 0), (7, 0), (9, 0)],
#  [(3, 1), (4, 1), (15, 1), (19, 1)]]

coll = LineCollection(lines, colors='k')

f, ax = plt.subplots()

ax.add_collection(coll)
# overlay with markers
ax.scatter(*zip(*chain.from_iterable(lines)), marker='+')

Note that you can pass colors to LineCollection and scatter if you want different colors. Also, you may use numpy to create the arrays of coordinates more efficiently.

Output:

发布评论

评论列表(0)

  1. 暂无评论