简体   繁体   English

如何在matplotlib的不同子图中重复绘图?

[英]How to repeat a plot in different subplots in matplotlib?

I have 我有

fig, (((ax1, ax2), (ax3, ax4))) = plt.subplots(ncols=2, nrows=2, 
                                               sharex='col', 
                                               sharey='row', 
                                               figsize=(12, 12))

and I want to repeat one plot, say P in all axes, something like: 我想重复一个图,在所有轴上说P,就像这样:

P.plot(ax = [ax1, ax2, ax3, ax4], facecolor = "none",
       edgecolor = "black")

without having to repeat the line for each plot. 无需为每个图重复该行。 Is there a way to do that? 有没有办法做到这一点?

Some people prefer to use map instead of for in python. 有些人更喜欢在Python中使用map而不是for So I suppose if the aim is to replace some canonical loop like 所以我想如果目的是取代一些规范的循环

for ax in [ax1, ax2, ax3, ax4]:
    geodf.plot(ax=ax)

you could do 你可以做

list(map(lambda ax: geodf.plot(ax=ax), [ax1, ax2, ax3, ax4]))

This is one way to do this using list comprehension method without having to write four separate plot commands explicitly . 这是使用列表推导方法执行此操作的一种方法,而不必显式编写四个单独的plot命令。 I am using a DataFrame as p to be consistent with your problem. 我使用DataFrame作为p与您的问题一致。 You can try replacing df with your p variable. 您可以尝试使用p变量替换df

import pandas as pd
import matplotlib.pyplot as plt

fig, (((ax1, ax2), (ax3, ax4))) = plt.subplots(ncols=2, nrows=2, 
                                               sharex='col', 
                                               sharey='row', 
                                               figsize=(8, 8))

df = pd.DataFrame({"x": [1, 2, 3, 4],
                   "y" : [1, 4, 9, 16]})

_ = [df.plot(x="x", y="y", ax=ax) for ax in [ax1, ax2, ax3, ax4]]
plt.show()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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