Matplotlib:创建两个子图,每个子图对应两个y轴

时间:2017-06-29 13:03:45

标签: python matplotlib plot

This matplotlib tutorial显示了如何使用两个y轴(两个不同的比例)创建绘图:

import numpy as np
import matplotlib.pyplot as plt


def two_scales(ax1, time, data1, data2, c1, c2):

    ax2 = ax1.twinx()

    ax1.plot(time, data1, color=c1)
    ax1.set_xlabel('time (s)')
    ax1.set_ylabel('exp')

    ax2.plot(time, data2, color=c2)
    ax2.set_ylabel('sin')
    return ax1, ax2


# Create some mock data
t = np.arange(0.01, 10.0, 0.01)
s1 = np.exp(t)
s2 = np.sin(2 * np.pi * t)

# Create axes
fig, ax = plt.subplots()
ax1, ax2 = two_scales(ax, t, s1, s2, 'r', 'b')


# Change color of each axis
def color_y_axis(ax, color):
    """Color your axes."""
    for t in ax.get_yticklabels():
        t.set_color(color)
    return None

color_y_axis(ax1, 'r')
color_y_axis(ax2, 'b')
plt.show()

结果如下: enter image description here

我的问题:你如何修改代码来创建两个这样的子图,只是水平对齐? 我会做类似

的事情
fig, ax = plt.subplots(1,2,figsize=(15, 8))
plt.subplot(121)
###plot something here
plt.subplot(122)
###plot something here

但是,如何确保调用创建轴的fig, ax = plt.subplots()不会与您调用的fig, ax = plt.subplots(1,2,figsize=(15, 8))冲突以创建水平对齐的画布?

2 个答案:

答案 0 :(得分:5)

您可以创建两个子图using FluentValidation; using Ninject; using System; using System.Linq; class Program { static void Main(string[] args) { // Set up the DI Container. var kernel = new StandardKernel(); kernel.Bind<IValidator<Customer>>().To<CustomerValidator>().InSingletonScope(); var nInjectvalidationFactory = kernel.Get<NInjectValidatorFactory>(); var customer = kernel.Get<Customer>(); var customerValidator = nInjectvalidationFactory.GetValidator<Customer>(); var results = customerValidator.Validate(customer); if (!results.IsValid) results.Errors.ToList().ForEach(e => { Console.WriteLine(e.ErrorMessage); Console.WriteLine(e.ErrorCode); Console.WriteLine(e.PropertyName); Console.WriteLine(e.ResourceName); Console.WriteLine(e.Severity); } ); Console.ReadLine(); } } 并将fig, (ax1, ax2) = plt.subplots(1,2)应用于每个子图。

two_scales

enter image description here

答案 1 :(得分:1)

这就是你想要的吗?

[...]
# Create some mock data
t = np.arange(0.01, 10.0, 0.01)
s1 = np.exp(t)
s2 = np.sin(2 * np.pi * t)

# Create axes
ax = plt.subplot(2,2,1)
ax1, ax2 = two_scales(ax, t, s1, s2, 'r', 'b')

ax = plt.subplot(2,2,2)
ax1, ax2 = two_scales(ax, t, s1, s2, 'r', 'b')
[...]

enter image description here