コード例 #1
0
    def __call__(self, inputs):
        from pylab import text
        from matplotlib.font_manager import FontProperties as FP
        kwds = {}
        #kwds['text'] = self.get_input('text')
        kwds['fontsize'] = self.get_input('fontsize')
        kwds['alpha'] = self.get_input('alpha')
        kwds['color'] = self.get_input('color')
        kwds['backgroundcolor'] = self.get_input('backgroundcolor')
        kwds['rotation'] = self.get_input('rotation')
        kwds['fontproperties'] = FP(**self.get_input('fontproperties'))
        for key, value in self.get_input('kwargs').iteritems():
            try:
                kwds[key] = value
            except:
                print 'key already defined. skip it'
                pass

        #res = text(0,0, self.get_input('text'), **kwds)

        return (kwds, )
コード例 #2
0
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 14 13:14:08 2020

@author: cdragon-ljl
"""

from matplotlib import pyplot as plt
from matplotlib.font_manager import FontProperties as FP

#添加中文字体
font = FP(fname=r"c:\windows\fonts\simsun.ttc", size=15)

plt.figure(figsize=(30, 10), dpi=80)

x_3 = range(1, 32)
y_3 = [
    11, 17, 16, 11, 12, 11, 12, 6, 6, 7, 8, 9, 12, 15, 14, 17, 18, 21, 16, 17,
    20, 14, 15, 15, 15, 19, 21, 22, 22, 22, 23
]
x_10 = range(41, 72)
y_10 = [
    26, 26, 28, 19, 21, 17, 16, 19, 18, 20, 20, 19, 22, 23, 17, 20, 21, 20, 22,
    15, 11, 15, 5, 13, 17, 10, 11, 13, 12, 13, 6
]

#绘制散点图
plt.scatter(x_3, y_3, label="3月份")
plt.scatter(x_10, y_10, label="10月份")

#调整x轴的刻度
コード例 #3
0
data = dataset.Appliances
#print(data.head())
#print(data.describe())

# 统计各列缺失值总数
#missing = dataset.isnull().sum()
#print(missing)

# 绘图查看
font1 = {
    'family': 'Times New Roman',
    'color': 'k',
    'weight': 'normal',
    'size': 15,
}
font2 = FP('Times New Roman', size=15)
'''
plt.figure(figsize=(10,4))
plt.hist(data,bins=50)
plt.xlabel('Wh',fontdict=font1)
plt.ylabel('Frequency',fontdict=font1)
plt.xticks([0,200,400,600,800,1000],['0','200','400','600','800','1000'],fontproperties=font2)
plt.yticks([0,1000,2000,3000,4000,5000,6000,],['0','1000','2000','3000','4000','5000','6000'],fontproperties=font2)
plt.savefig('图3直方图.svg',bbox_inches='tight')
'''
'''
plt.figure(figsize=(2,10))
sns.boxplot(data=dataset.iloc[:,1:2])
#plt.xlabel('load',fontdict=font1)
plt.xticks([])
plt.xlabel('Appliances',fontdict=font1)
コード例 #4
0
"""
    Using python to draw tracking results compared with groundtruth
"""

import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties as FP
import numpy as np

efp = FP('Times New Roman', size=13)

#### load groundtruth txt file
gt = np.loadtxt("groundtruth.txt")
print(type(gt), gt.shape)

timestamp = gt[:, 0]
gt_pos_x = gt[:, 1]
gt_pos_y = gt[:, 2]
gt_pos_z = gt[:, 3]
gt_heading = gt[:, 4]

### load track results
track = np.loadtxt("track_results.txt")
tr_pos_x = track[:, 1]
tr_pos_y = track[:, 2]
tr_v = track[:, 3]
tr_heading = track[:, 4]
tr_yaw_rate = track[:, 5]

### ------Begin plot-------
plt.figure('position')
plt.grid(linestyle="-.")
コード例 #5
0
ファイル: ti_dhdl.py プロジェクト: xiki-tempula/alchemlyb
def plot_ti_dhdl(dhdl_data, labels=None, colors=None, units='kT', ax=None):
    '''Plot the dhdl of TI.

    Parameters
    ----------
    dhdl_data : :class:`~alchemlyb.estimators.TI` or list
        One or more :class:`~alchemlyb.estimators.TI` estimator, where the
        dhdl value will be taken from.
    labels : List
        list of labels for labelling all the alchemical transformations.
    colors : List
        list of colors for plotting all the alchemical transformations.
        Default: ['r', 'g', '#7F38EC', '#9F000F', 'b', 'y']
    units : str
        The label for the unit of the estimate. Default: "kT"
    ax : matplotlib.axes.Axes
        Matplotlib axes object where the plot will be drawn on. If ``ax=None``,
        a new axes will be generated.

    Returns
    -------
    matplotlib.axes.Axes
        An axes with the TI dhdl drawn.

    Note
    ----
    The code is taken and modified from
    `Alchemical Analysis <https://github.com/MobleyLab/alchemical-analysis>`_.


    .. versionchanged:: 0.5.0
        The `units` will be used to change the underlying data instead of only
        changing the figure legend.

    .. versionadded:: 0.4.0
    '''
    # Make it into a list
    # separate_dhdl method is used so that the input for the actual plotting
    # Function are a uniformed list of series object which only contains one
    # lambda.
    if not isinstance(dhdl_data, list):
        dhdl_list = dhdl_data.separate_dhdl()
    else:
        dhdl_list = []
        for dhdl in dhdl_data:
            dhdl_list.extend(dhdl.separate_dhdl())

    # Convert unit
    new_unit = []
    convert = get_unit_converter(units)
    for dhdl in dhdl_list:
        new_unit.append(convert(dhdl))

    dhdl_list = new_unit
    if ax is None:
        fig, ax = plt.subplots(figsize=(8, 6))

    ax.spines['bottom'].set_position('zero')
    ax.spines['top'].set_color('none')
    ax.spines['right'].set_color('none')
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')

    for k, spine in ax.spines.items():
        spine.set_zorder(12.2)

    # Make level names
    if labels is None:
        lv_names2 = []
        for dhdl in dhdl_list:
            # Assume that the dhdl has only one columns
            lv_names2.append(dhdl.name.capitalize())
    else:
        if len(labels) == len(dhdl_list):
            lv_names2 = labels
        else:  # pragma: no cover
            raise ValueError(
                'Length of labels ({}) should be the same as the number of data ({})'
                .format(len(labels), len(dhdl_list)))

    if colors is None:
        colors = ['r', 'g', '#7F38EC', '#9F000F', 'b', 'y']
    else:
        if len(colors) >= len(dhdl_list):
            pass
        else:  # pragma: no cover
            raise ValueError(
                'Number of colors ({}) should be larger than the number of data ({})'
                .format(len(labels), len(dhdl_list)))

    # Get the real data out
    xs, ndx, dx = [0], 0, 0.001
    min_y, max_y = 0, 0
    for dhdl in dhdl_list:
        x = dhdl.index.values
        y = dhdl.values.ravel()

        min_y = min(y.min(), min_y)
        max_y = max(y.max(), max_y)

        for i in range(len(x) - 1):
            if i % 2 == 0:
                ax.fill_between(x[i:i + 2] + ndx,
                                0,
                                y[i:i + 2],
                                color=colors[ndx],
                                alpha=1.0)
            else:
                ax.fill_between(x[i:i + 2] + ndx,
                                0,
                                y[i:i + 2],
                                color=colors[ndx],
                                alpha=0.5)

        xlegend = [-100 * wnum for wnum in range(len(lv_names2))]
        ax.plot(xlegend, [0 * wnum for wnum in xlegend],
                ls='-',
                color=colors[ndx],
                label=lv_names2[ndx])
        xs += (x + ndx).tolist()[1:]
        ndx += 1

    # Make sure the tick labels are not overcrowded.
    xs = np.array(xs)
    dl_mat = np.array([xs - i for i in xs])
    ri = range(len(xs))

    def getInd(r=ri, z=[0]):
        primo = r[0]
        min_dl = ndx * 0.02 * 2**(primo > 10)
        if dl_mat[primo].max() < min_dl:
            return z
        for i in r:  # pragma: no cover
            for j in range(len(xs)):
                if dl_mat[i, j] > min_dl:
                    z.append(j)
                    return getInd(ri[j:], z)

    xt = []
    for i in range(len(xs)):
        if i in getInd():
            xt.append(i)
        else:
            xt.append('')

    plt.xticks(xs[1:], xt[1:], fontsize=10)
    ax.yaxis.label.set_size(10)

    # Remove the abscissa ticks and set up the axes limits.
    for tick in ax.get_xticklines():
        tick.set_visible(False)
    ax.set_xlim(0, ndx)
    min_y *= 1.01
    max_y *= 1.01

    # Modified so that the x label won't conflict with the lambda label
    min_y -= (max_y - min_y) * 0.1

    ax.set_ylim(min_y, max_y)

    for i, j in zip(xs[1:], xt[1:]):
        ax.annotate(
            ('%.2f' % (i - 1.0 if i > 1.0 else i) if not j == '' else ''),
            xy=(i, 0),
            size=10,
            rotation=90,
            va='bottom',
            ha='center',
            color='#151B54')
    if ndx > 1:
        lenticks = len(ax.get_ymajorticklabels()) - 1
        if min_y < 0: lenticks -= 1
        if lenticks < 5:  # pragma: no cover
            from matplotlib.ticker import AutoMinorLocator as AML
            ax.yaxis.set_minor_locator(AML())
    ax.grid(which='both', color='w', lw=0.25, axis='y', zorder=12)
    ax.set_ylabel(
        r'$\langle{\frac{\partial U}{\partial\lambda}}\rangle_{\lambda}$' +
        '({})'.format(units),
        fontsize=20,
        color='#151B54')
    ax.annotate(r'$\mathit{\lambda}$',
                xy=(0, 0),
                xytext=(0.5, -0.05),
                size=18,
                textcoords='axes fraction',
                va='top',
                ha='center',
                color='#151B54')
    lege = ax.legend(prop=FP(size=14), frameon=False, loc=1)
    for l in lege.legendHandles:
        l.set_linewidth(10)
    return ax
コード例 #6
0
import numpy as np
import csv
import math
from scipy import interpolate
from matplotlib import pyplot as plt
from matplotlib.ticker import LinearLocator, MultipleLocator, FormatStrFormatter
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import pandas as pd
import seaborn as sns
from sklearn.preprocessing import MinMaxScaler

from matplotlib.font_manager import FontProperties as FP

plt.rc('font', family='Times New Roman')
font_TNM = FP(fname=r"C:\Windows\Fonts\times.ttf", size=10.5)

Altitude_scalar = 12.44
Latitude_scalar = 52.13
Longitude_scalar = 39.78
Altitude_xishu = 1.32
Latitude_xishu = 1.08
Longitude_xishu = 1.08

# pred_true_values line
"""

data_LSTM = pd.read_csv(r"D:\轨迹预测\prediction\LSTM\pred_y.csv")
data_GRU = pd.read_csv(r"D:\轨迹预测\prediction\GRU\pred_y.csv")
data_BP = pd.read_csv(r"D:\轨迹预测\prediction\BP\pred_y10.csv")
data_SVR = pd.read_csv(r"D:\轨迹预测\prediction\SVR\pred_y.csv")
コード例 #7
0
import numpy as np
import pandas as pd
import pymc as pm
import os
import matplotlib.pyplot as plt
from pylab import *
from scipy.stats.mstats import mquantiles
from matplotlib.font_manager import FontManager as FM
from matplotlib.font_manager import FontProperties as FP
myfont = FP(fname='D://Lib//site-packages//matplotlib//'
            'mpl-data//fonts//ttf//vera.ttf')
mpl.rcParams['font.sans-serif'] = ['SimHei']


# 逻辑斯蒂函数
def logistic(x, beta, alpha=0):
    return 1.0 / (1.0 + np.exp((beta * x) + alpha))


# 散点图
def scatter_figure(data, index):

    plt.scatter(data[:, 0], data[:, 2], color='black', alpha=0.5)
    plt.yticks([0, 1])
    plt.ylabel(u"销售点", fontproperties=myfont)
    plt.xlabel("属性距离", fontproperties=myfont)
    plt.title(u'销售点与每个县城相关属性距离散点图', fontproperties=myfont)
    plt.xticks(data[:, 0],
               index,
               size='small',
               fontproperties=myfont,
コード例 #8
0
"""
 Learn how to use subplot to draw multiple plots in one figure
 References: https://matplotlib.org/gallery/subplots_axes_and_figures/subplot.html
"""
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties as FP
import numpy as np

mpl.rcParams['font.family'] = 'sans-serif'
mpl.rcParams['font.sans-serif'] = 'NSimSun,Times New Roman'
efp = FP('Times New Roman')
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)

y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

plt.subplot(2, 1, 1)
plt.plot(x1, y1, 'o-')
plt.title('A tale of 2 subplots', fontweight='bold', fontproperties=efp)
plt.ylabel('Damped oscillation', fontproperties=efp)

plt.subplot(2, 1, 2)
plt.plot(x2, y2, '.-')
plt.xlabel('time [s]')
plt.ylabel('Undamped', fontproperties=efp)

plt.show()
コード例 #9
0
    d = y - gt_pos_y[idx]
    delta_gt_pos_y.append(d)

vx = [x / t for x, t in zip(delta_gt_pos_x, delta_t)]
vy = [y / t for y, t in zip(delta_gt_pos_y, delta_t)]
v = [cmath.sqrt(a**2 + b**2) for a, b in zip(vx, vy)]
v.insert(0, 0.0)

### load track results
track = np.loadtxt("track_results.txt")
tr_pos_x = track[:, 1]
tr_pos_y = track[:, 2]
tr_v = track[:, 3]
tr_heading = track[:, 4]
tr_yaw_rate = track[:, 5]

frame = np.arange(len(v))

mpl.rcParams['font.family'] = 'sans-serif'
mpl.rcParams['font.sans-serif'] = 'SimHei,Times New Roman'
cfp = FP('SimHei', size=15)

plt.figure("v")
plt.grid(linestyle="-.", color='gray')
plt.plot(frame, tr_v * 3.6, '-', color='blue', label="UKF输出")
plt.plot(frame, np.array(v) * 3.6, color='red', label="直接计算")
plt.xlabel("Frames", fontsize=15)
plt.ylabel("Velocity [km/h]", fontsize=15)
plt.legend(prop=cfp, ncol=2)
# plt.savefig("v.svg", format="svg")
plt.show()
コード例 #10
0
ファイル: dF_state.py プロジェクト: xiki-tempula/alchemlyb
def plot_dF_state(estimators,
                  labels=None,
                  colors=None,
                  units='kT',
                  orientation='portrait',
                  nb=10):
    '''Plot the dhdl of TI.

    Parameters
    ----------
    estimators : :class:`~alchemlyb.estimators` or list
        One or more :class:`~alchemlyb.estimators`, where the
        dhdl value will be taken from. For more than one estimators
        with more than one alchemical transformation, a list of list format
        is used.
    labels : List
        list of labels for labelling different estimators.
    colors : List
        list of colors for plotting different estimators.
    units : str
        The unit of the estimate. Default: "kT"
    orientation : string
        The orientation of the figure. Can be `portrait` or `landscape`
    nb : int
        Maximum number of dF states in one row in the `portrait` mode

    Returns
    -------
    matplotlib.figure.Figure
        An Figure with the dF states drawn.

    Note
    ----
    The code is taken and modified from
    `Alchemical Analysis <https://github.com/MobleyLab/alchemical-analysis>`_.


    .. versionchanged:: 0.5.0
        The `units` will be used to change the underlying data instead of only
        changing the figure legend.

    .. versionadded:: 0.4.0
    '''
    try:
        len(estimators)
    except TypeError:
        estimators = [
            estimators,
        ]

    formatted_data = []
    for dhdl in estimators:
        try:
            len(dhdl)
            formatted_data.append(dhdl)
        except TypeError:
            formatted_data.append([
                dhdl,
            ])
    estimators = formatted_data

    # Get the dF
    dF_list = []
    error_list = []
    max_length = 0
    convert = get_unit_converter(units)
    for dhdl_list in estimators:
        len_dF = sum([len(dhdl.delta_f_) - 1 for dhdl in dhdl_list])
        if len_dF > max_length:
            max_length = len_dF
        dF = []
        error = []
        for dhdl in dhdl_list:
            for i in range(len(dhdl.delta_f_) - 1):
                dF.append(convert(dhdl.delta_f_).iloc[i, i + 1])
                error.append(convert(dhdl.d_delta_f_).iloc[i, i + 1])

        dF_list.append(dF)
        error_list.append(error)

    # Get the determine orientation
    if orientation == 'landscape':
        if max_length < 8:
            fig, ax = plt.subplots(figsize=(8, 6))
        else:
            fig, ax = plt.subplots(figsize=(max_length, 6))
        axs = [
            ax,
        ]
        xs = [
            np.arange(max_length),
        ]
    elif orientation == 'portrait':
        if max_length < nb:
            xs = [
                np.arange(max_length),
            ]
            fig, ax = plt.subplots(figsize=(8, 6))
            axs = [
                ax,
            ]
        else:
            xs = np.array_split(np.arange(max_length), max_length / nb + 1)
            fig, axs = plt.subplots(nrows=len(xs), figsize=(8, 6))
        mnb = max([len(i) for i in xs])
    else:
        raise ValueError(
            "Not recognising {}, only supports 'landscape' or 'portrait'.".
            format(orientation))

    # Sort out the colors
    if colors is None:
        colors_dict = {
            'TI': '#C45AEC',
            'TI-CUBIC': '#33CC33',
            'DEXP': '#F87431',
            'IEXP': '#FF3030',
            'GINS': '#EAC117',
            'GDEL': '#347235',
            'BAR': '#6698FF',
            'UBAR': '#817339',
            'RBAR': '#C11B17',
            'MBAR': '#F9B7FF'
        }
        colors = []
        for dhdl in estimators:
            dhdl = dhdl[0]
            if isinstance(dhdl, TI):
                colors.append(colors_dict['TI'])
            elif isinstance(dhdl, BAR):
                colors.append(colors_dict['BAR'])
            elif isinstance(dhdl, MBAR):
                colors.append(colors_dict['MBAR'])
    else:
        if len(colors) >= len(estimators):
            pass
        else:
            raise ValueError(
                'Number of colors ({}) should be larger than the number of data ({})'
                .format(len(colors), len(estimators)))

    # Sort out the labels
    if labels is None:
        labels = []
        for dhdl in estimators:
            dhdl = dhdl[0]
            if isinstance(dhdl, TI):
                labels.append('TI')
            elif isinstance(dhdl, BAR):
                labels.append('BAR')
            elif isinstance(dhdl, MBAR):
                labels.append('MBAR')
    else:
        if len(labels) == len(estimators):
            pass
        else:
            raise ValueError(
                'Length of labels ({}) should be the same as the number of data ({})'
                .format(len(labels), len(estimators)))

    # Plot the figure
    width = 1. / (len(estimators) + 1)
    elw = 30 * width
    ndx = 1
    for x, ax in zip(xs, axs):
        lines = []
        for i, (dF, error) in enumerate(zip(dF_list, error_list)):
            y = [dF[j] for j in x]
            ye = [error[j] for j in x]
            if orientation == 'landscape':
                lw = 0.1 * elw
            elif orientation == 'portrait':
                lw = 0.05 * elw
            line = ax.bar(x + len(lines) * width,
                          y,
                          width,
                          color=colors[i],
                          yerr=ye,
                          lw=lw,
                          error_kw=dict(elinewidth=elw,
                                        ecolor='black',
                                        capsize=0.5 * elw))
            lines += (line[0], )
        for dir in ['left', 'right', 'top', 'bottom']:
            if dir == 'left':
                ax.yaxis.set_ticks_position(dir)
            else:
                ax.spines[dir].set_color('none')

        if orientation == 'landscape':
            plt.yticks(fontsize=8)
            ax.set_xlim(x[0] - width, x[-1] + len(lines) * width)
            plt.xticks(x + 0.5 * width * len(estimators),
                       tuple(['%d--%d' % (i, i + 1) for i in x]),
                       fontsize=8)
        elif orientation == 'portrait':
            plt.yticks(fontsize=10)
            ax.xaxis.set_ticks([])
            for i in x + 0.5 * width * len(estimators):
                ax.annotate(r'$\mathrm{%d-%d}$' % (i, i + 1),
                            xy=(i, 0),
                            xycoords=('data', 'axes fraction'),
                            xytext=(0, -2),
                            size=10,
                            textcoords='offset points',
                            va='top',
                            ha='center')
            ax.set_xlim(x[0] - width,
                        x[-1] + len(lines) * width + (mnb - len(x)))
        ndx += 1
    x = np.arange(max_length)

    ax = plt.gca()

    for tick in ax.get_xticklines():
        tick.set_visible(False)
    if orientation == 'landscape':
        leg = plt.legend(lines,
                         labels,
                         loc=3,
                         ncol=2,
                         prop=FP(size=10),
                         fancybox=True)
        plt.title('The free energy change breakdown', fontsize=12)
        plt.xlabel('States', fontsize=12, color='#151B54')
        plt.ylabel(r'$\Delta G$ ({})'.format(units),
                   fontsize=12,
                   color='#151B54')
    elif orientation == 'portrait':
        leg = ax.legend(lines,
                        labels,
                        loc=0,
                        ncol=2,
                        prop=FP(size=8),
                        title=r'$\Delta G$ ({})'.format(units) +
                        r'$\mathit{vs.}$ lambda pair',
                        fancybox=True)

    leg.get_frame().set_alpha(0.5)
    return fig
コード例 #11
0
ファイル: convergence.py プロジェクト: xiki-tempula/alchemlyb
def plot_convergence(*data, units='kT', ax=None):
    """Plot the forward and backward convergence.

    The input could be the result from
    :func:`~alchemlyb.convergence.forward_backward_convergence` or it could
    be given explicitly as `forward`, `forward_error`, `backward`,
    `backward_error`.

    `forward`: A list of free energy estimate from the first X% of data,
    where `forward_error` is the corresponding error.
    
    `backward`: A list of free energy estimate from the last X% of data.,
    where `backward_error` is the corresponding error.

    These four array_like objects should have the same
    shape and can be used as input for the
    :func:`matplotlib.pyplot.errorbar`.

    Parameters
    ----------
    data : Dataframe or 4 array_like objects
        Output Dataframe from
        :func:`~alchemlyb.convergence.forward_backward_convergence`.
        Or given explicitly as `forward`, `forward_error`, `backward`,
        `backward_error` see :ref:`plot_convergence <plot_convergence>`.
    units : str
        The label for the unit of the estimate. Default: "kT"
    ax : matplotlib.axes.Axes
        Matplotlib axes object where the plot will be drawn on. If ``ax=None``,
        a new axes will be generated.

    Returns
    -------
    matplotlib.axes.Axes
        An axes with the forward and backward convergence drawn.

    Note
    ----
    The code is taken and modified from
    `Alchemical Analysis <https://github.com/MobleyLab/alchemical-analysis>`_.

    If `data` is not an :class:pandas.Dataframe` produced by
    :func:`~alchemlyb.convergence.forward_backward_convergence`,
    the unit will be adjusted according to the units
    variable. Otherwise, the units variable is for labelling only.
    Changing it doesn't change the unit of the underlying variable.


    .. versionchanged:: 0.6.0
        data now takes in dataframe

    .. versionadded:: 0.4.0
    """
    if len(data) == 1 and isinstance(data[0], pd.DataFrame):
        dataframe = get_unit_converter(units)(data[0])
        forward = dataframe['Forward'].to_numpy()
        forward_error = dataframe['Forward_Error'].to_numpy()
        backward = dataframe['Backward'].to_numpy()
        backward_error = dataframe['Backward_Error'].to_numpy()
    else:
        try:
            forward, forward_error, backward, backward_error = data
        except ValueError:  # pragma: no cover
            raise ValueError('Ensure all four of forward, forward_error, '
                             'backward, backward_error are supplied.')

    if ax is None:  # pragma: no cover
        fig, ax = plt.subplots(figsize=(8, 6))

    plt.setp(ax.spines['bottom'], color='#D2B9D3', lw=3, zorder=-2)
    plt.setp(ax.spines['left'], color='#D2B9D3', lw=3, zorder=-2)

    for dire in ['top', 'right']:
        ax.spines[dire].set_color('none')

    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')

    f_ts = np.linspace(0, 1, len(forward) + 1)[1:]
    r_ts = np.linspace(0, 1, len(backward) + 1)[1:]

    line0 = ax.fill_between([0, 1],
                            backward[-1] - backward_error[-1],
                            backward[-1] + backward_error[-1],
                            color='#D2B9D3',
                            zorder=1)
    line1 = ax.errorbar(
        f_ts,
        forward,
        yerr=forward_error,
        color='#736AFF',
        lw=3,
        zorder=2,
        marker='o',
        mfc='w',
        mew=2.5,
        mec='#736AFF',
        ms=12,
    )
    line2 = ax.errorbar(
        r_ts,
        backward,
        yerr=backward_error,
        color='#C11B17',
        lw=3,
        zorder=3,
        marker='o',
        mfc='w',
        mew=2.5,
        mec='#C11B17',
        ms=12,
    )

    plt.xticks(r_ts[::2], fontsize=10)
    plt.yticks(fontsize=10)

    ax.legend((line1[0], line2[0]), ('Forward', 'Reverse'),
              loc=9,
              prop=FP(size=18),
              frameon=False)
    ax.set_xlabel(r'Fraction of the simulation time',
                  fontsize=16,
                  color='#151B54')
    ax.set_ylabel(r'$\Delta G$ ({})'.format(units),
                  fontsize=16,
                  color='#151B54')
    plt.xticks(f_ts, ['%.2f' % i for i in f_ts])
    plt.tick_params(axis='x', color='#D2B9D3')
    plt.tick_params(axis='y', color='#D2B9D3')
    return ax
コード例 #12
0
del a_limit['banci12']
'''
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
from matplotlib.font_manager import FontProperties as FP

mpl.rcParams['font.family'] = 'sans-serif'
mpl.rcParams[
    'font.sans-serif'] = 'NSimSun,Times New Roman'  #//中文除外的设置成New Roman,中文设置成宋体

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

fig = plt.figure()
cfp = FP('NSimSun', size=12)
efp = FP('Times New Roman', size=12)

ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)
ax4 = fig.add_subplot(2, 2, 4)

ax1.plot(a, color='black')
ax1.set_ylim([200, 1200])
ax1.set_yticklabels(['250', '250', '500', '750', '1 000'], fontproperties=efp)

ax1.set_xticks(range(0, 12))
ax1.set_xticklabels(range(1, 12))
ax1.set_xlabel(u'站点', fontsize=13.5)
ax1.set_ylabel(u'车头时距/s', fontsize=13.5)