Python中的一个图形中的多个图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21254472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:24:36  来源:igfitidea点击:

multiple plot in one figure in Python

pythonmatplotlibplot

提问by user3183660

I am new to python and am trying to plot multiple lines in the same figure using matplotlib. Value of my Y axis is stored in a dictionary and I make corresponding values in X axis in my following code

我是 python 的新手,正在尝试使用 matplotlib 在同一图中绘制多条线。我的 Y 轴的值存储在字典中,我在下面的代码中在 X 轴上创建了相应的值

My code is like this:

我的代码是这样的:

for i in range(len(ID)):
AxisY= PlotPoints[ID[i]]
if len(AxisY)> 5:
    AxisX= [len(AxisY)]
    for i in range(1,len(AxisY)):
        AxisX.append(AxisX[i-1]-1)
    plt.plot(AxisX,AxisY)
    plt.xlabel('Lead Time (in days)')
    plt.ylabel('Proportation of Events Scheduled')
    ax = plt.gca()
    ax.invert_xaxis()
    ax.yaxis.tick_right()
    ax.yaxis.set_label_position("right")
    plt.show()

But I am getting separate figures with single plot one by one. Can anybody help me figure our what is wrong with my code? Why can't I produce multiple line plotting? Thanks a lot!

但我得到一个单独的图形一个一个地。有人可以帮我弄清楚我的代码有什么问题吗?为什么我不能生成多线绘图?非常感谢!

采纳答案by Games Brainiac

This is very simple to do:

这很简单:

import matplotlib.pyplot as plt

plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.legend(loc='best')
plt.show()

You can keep adding plt.plotas many times as you like. As for line type, you need to first specify the color. So for blue, it's b. And for a normal line it's -. An example would be:

您可以根据需要继续添加任意plt.plot次数。至于line type,您需要先指定颜色。所以对于蓝色,它是b。对于普通线路,它是-. 一个例子是:

plt.plot(total_lengths, sort_times_heap, 'b-', label="Heap")

回答by Kraay89

EDIT: I just realised after reading your question again, that i did not answer your question. You want to enter multiple lines in the same plot. However, I'll leave it be, because this served me very well multiple times. I hope you find usefull someday

编辑:再次阅读您的问题后,我才意识到我没有回答您的问题。您想在同一个图中输入多条线。但是,我会保留它,因为这多次为我提供了很好的帮助。我希望有一天你会觉得有用

I found this a while back when learning python

我在学习 python 时发现了这个

import matplotlib as plt
import matplotlib.gridspec as gridspec

fig = plt.figure() 
# create figure window

gs = gridspec.GridSpec(a, b)
# Creates grid 'gs' of a rows and b columns 


ax = plt.subplot(gs[x, y])
# Adds subplot 'ax' in grid 'gs' at position [x,y]


ax.set_ylabel('Foo') #Add y-axis label 'Foo' to graph 'ax' (xlabel for x-axis)


fig.add_subplot(ax) #add 'ax' to figure

you can make different sizes in one figure as well, use slices in that case:

您也可以在一个图中制作不同的尺寸,在这种情况下使用切片:

 gs = gridspec.GridSpec(3, 3)
 ax1 = plt.subplot(gs[0,:]) # row 0 (top) spans all(3) columns

consult the docsfor more help and examples. This little bit i typed up for myself once, and is very much based/copied from the docs as well. Hope it helps... I remember it being a pain in the #$% to get acquainted with the slice notation for the different sized plots in one figure. After that i think it's very simple :)

查阅文档以获得更多帮助和示例。这一点我曾经为自己输入过,并且也非常基于/复制自文档。希望它有所帮助......我记得熟悉一个图中不同大小的图的切片符号是一种痛苦的#$%。之后我认为这很简单:)

回答by Stian

Since I don't have a high enough reputation to comment I'll answer liang question on Feb 20 at 10:01 as an answer to the original question.

由于我没有足够高的声誉来发表评论,我将在 2 月 20 日 10:01 回答梁问题作为对原始问题的回答。

In order for the for the line labels to show you need to add plt.legend to your code. to build on the previous example above that also includes title, ylabel and xlabel:

为了显示行标签,您需要将 plt.legend 添加到您的代码中。以上面还包括标题、ylabel 和 xlabel 的上一个示例为基础:

import matplotlib.pyplot as plt

plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.title('title')
plt.ylabel('ylabel')
plt.xlabel('xlabel')
plt.legend()
plt.show()

回答by PatrickT

The OP states that each plot element overwrites the previous one rather than being combined into a single plot. This can happen even with one of the many suggestions made by other answers. If you select several lines and run them together, say:

OP 指出,每个绘图元素都会覆盖前一个元素,而不是合并为一个绘图元素。即使使用其他答案提出的众多建议之一,也可能发生这种情况。如果您选择多行并将它们一起运行,请说:

plt.plot(<X>, <Y>)
plt.plot(<X>, <Z>)

the plot elements will typically be rendered together, one layer on top of the other. But if you execute the code line-by-line, each plot will overwrite the previous one.

情节元素通常会一起渲染,一层在另一层之上。但是如果你一行一行地执行代码,每个图都会覆盖前一个。

This perhaps is what happened to the OP. It just happened to me: I had set up a new key binding to execute code by a single key press (on spyder), but my key binding was executing only the current line. The solution was to select lines by whole blocks or to run the whole file.

这也许就是发生在 OP 上的事情。它刚好发生在我身上:我已经设置了一个新的键绑定来通过单个按键 (on spyder)执行代码,但是我的键绑定只执行当前行。解决方案是按整个块选择行或运行整个文件。