【问题标题】:Add multiples graphs in one figure在一个图中添加多个图表
【发布时间】:2020-10-01 14:00:54
【问题描述】:

我正在使用 Jupiter 学习 Python,但我正在努力将这些图表放在一个图中。这是我到目前为止所拥有的......

我的图表代码(我有三个图表,它们仅在颜色和线条与点方面有所不同):

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

one = plt.figure()
plt.plot(x_v, y_v, '#008000') #change color using hex strings 
plt.xlabel('x')
plt.ylabel('y')
plt.show()
    
two = plt.figure()
plt.plot(x_v, y_v, linestyle='none', marker='o', markersize=0.5)
plt.show()

three = plt.figure()
plt.plot(x_v, y_v, linestyle='none', marker='o', markersize=0.5, color = 'yellow')
plt.show()

到目前为止,这是我将其设为一个数字的代码...我想知道是否应该将其放入 np.arange 并绘制它,但我似乎无法让它工作... .

def f(x):
    return one

def g(x):
    return two

def h(x):
    return three

如果有人可以提供帮助,那将非常有用!谢谢!

【问题讨论】:

    标签: python matplotlib jupyter-notebook


    【解决方案1】:

    你可以使用plt.subplots:

    fig, (ax1, ax2, ax3) = plt.subplots(figsize=(15, 5), ncols=3)
    ax1.plot(x_v, y_v, '#008000')
    ax1.set_xlabel('x')
    ax1.set_ylabel('y')
    
    ax2.plot(x_v, y_v, linestyle='none', marker='o', markersize=0.5)
    
    ax3.plot(x_v, y_v, linestyle='none', marker='o', markersize=0.5, color = 'yellow')
    

    【讨论】:

      【解决方案2】:

      这是使用plt.subplots 处理多个图的一种方法。我认为它很容易理解,并且可以很好地控制各个情节:

      import numpy as np
      import matplotlib.pyplot as plt
      
      #generating test data
      x = np.arange(0,9)
      y = np.arange(1,10)
      
      #defining figure layout (i.e. rows, columns, size, horizontal and vertical space between subplots
      fig,ax = plt.subplots(nrows=2,ncols=2,figsize=(15,7))
      plt.subplots_adjust(hspace=0.4,wspace=0.2)
      
      #first subplot (numbering can be read as 1st plot in a grid of 2x2)
      plt.subplot(2,2,1)
      plt.plot(x,y)
      
      #second subplot in a grid of 2x2
      plt.subplot(2,2,2)
      plt.plot(x,y,ls='--')
      
      #third subplot in a grid of 2x2
      plt.subplot(2,2,3)
      plt.scatter(x,y)
      
      #fourth subplot in a grid of 2x2
      plt.subplot(2,2,4)
      plt.plot(x,y)
      
      
      plt.tight_layout()
      plt.show()
      

      输出

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-07
        • 1970-01-01
        • 2012-03-15
        相关资源
        最近更新 更多