情节如何在相同的y轴上用不同的X阵列绘制多条线
我尝试使用Python中的绘图来绘制几行在同一图上具有自己的X值。
x1 = [1, 3, 5, 7, 9]
y1 = np.random.random(5)
x2 = [2, 4, 6, 8, 10]
y2 = np.random.random(5)
我想将其绘制在1到10的一个X轴上。
stackoverflow上的所有答案(例如 this )用熊猫数据框来描述解决方案,其中所有线(y1和y2)具有与每条线相对应的X值的相同数组。但是,在我的情况下,Y1和Y2具有相应的X值不同(尽管在相同的单元中)。
我该怎么做才能在情节中制作这样的情节?
I try to use plotly in python to plot several lines having their own X-values on the same graph for example.
x1 = [1, 3, 5, 7, 9]
y1 = np.random.random(5)
x2 = [2, 4, 6, 8, 10]
y2 = np.random.random(5)
I want to plot this on the one x-axis from 1 to 10.
All answers on StackOverFlow (like this) describe the solution with a pandas dataframe where all lines (y1 and y2) have the same array of x-values corresponding to each line. However, in my case y1 and y2 have different (though in the same units) corresponding x-values.
What can I do to make such a plot in plotly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您没有数据框架时,我认为最简单的方法是使用
plotly.graph_objects
。您也可以使用
plotly.express
模块,但是它需要更多代码来设置传说上的名称。在此文档页面 。
When you don't have a dataframe, I argue that the easiest way is to use
plotly.graph_objects
.You can also use the
plotly.express
module, however it requires a bit more code to set the names on the legends.Learn more at this documentation page.
只需在示例数据上使用一个 little 数据争吵,您就可以使用此行:
<
a href =“ https://i.sstatic.net/naius.png “ rel =“ nofollow noreferrer”>
争吵只是在您的两个数据范围内构建两个数据范围categories并将它们堆放到所谓的绘制表达精美的长形式。与所谓的广泛形式数据相反,不同类别的观察数是否不同。
完成代码:
With just a little bit of data wrangling on your example data, you can just use this single line:
And get this:
The wrangling is just building two dataframes out of your categegories and stacking them into a so-called long form which plotly express handles beautifully. Contrary to so-called wide form data, it won't matter if the different categories have a different number of observations.
Complete code: