Esempio n. 1
0
def _scale_fig_size(figsize, textsize, rows=1, cols=1):
    """Scale figure properties according to rows and cols.

    Parameters
    ----------
    figsize : float or None
        Size of figure in inches
    textsize : float or None
        fontsize
    rows : int
        Number of rows
    cols : int
        Number of columns

    Returns
    -------
    figsize : float or None
        Size of figure in inches
    fontsize : int
        fontsize
    linewidth : int
        linewidth
    markersize : int
        markersize
    """
    rc_width, rc_height = tuple(mpl.rc_params()['figure.figsize'])
    rc_fontsize = mpl.rc_params()['font.size']
    rc_linewidth = mpl.rc_params()['lines.linewidth']
    rc_markersize = mpl.rc_params()['lines.markersize']
    if figsize is None:
        width, height = rc_width, rc_height
        width = width * cols
        height = height * rows
    else:
        width, height = figsize

    if rows and cols > 1:
        fontsize = rc_fontsize
        linewidth = rc_linewidth
        markersize = rc_markersize
    else:
        scale_factor = ((width * height) / (rc_width * rc_height))**0.5
        fontsize = scale_factor * rc_fontsize
        linewidth = scale_factor * rc_linewidth
        markersize = scale_factor * rc_markersize

    if textsize is not None:
        fontsize = textsize

    return (width, height), fontsize, linewidth, markersize
def getImages_pylab(string_method, matrices, imageWidthInPixels, imageHeightInPixels):
    # Import system modules
    import matplotlib
    import pylab
    # Initialize
    images = []
    convertPixelLengthToInchLength = lambda x: x / float(matplotlib.rc_params()['figure.dpi'])
    imageWidthInInches = convertPixelLengthToInchLength(imageWidthInPixels)
    imageHeightInInches = convertPixelLengthToInchLength(imageHeightInPixels)
    imageDimensions = imageWidthInInches, imageHeightInInches
    # For each matrix,
    for matrix in matrices:
        # Create a new figure
        pylab.figure(figsize=imageDimensions)
        axes = pylab.axes()
        # Plot grayscale matrix
        method = getattr(axes, string_method)
        method(matrix, cmap=pylab.cm.gray)
        # Clear tick marks
        axes.set_xticks([])
        axes.set_yticks([])
        # Save image
        imageFile = StringIO.StringIO()
        pylab.savefig(imageFile, format='png')
        imageFile.seek(0)
        # Append
        images.append(Image.open(imageFile))
    # Return
    return images
def getImages_pylab(string_method, matrices, imageWidthInPixels,
                    imageHeightInPixels):
    # Import system modules
    import matplotlib
    import pylab
    # Initialize
    images = []
    convertPixelLengthToInchLength = lambda x: x / float(matplotlib.rc_params(
    )['figure.dpi'])
    imageWidthInInches = convertPixelLengthToInchLength(imageWidthInPixels)
    imageHeightInInches = convertPixelLengthToInchLength(imageHeightInPixels)
    imageDimensions = imageWidthInInches, imageHeightInInches
    # For each matrix,
    for matrix in matrices:
        # Create a new figure
        pylab.figure(figsize=imageDimensions)
        axes = pylab.axes()
        # Plot grayscale matrix
        method = getattr(axes, string_method)
        method(matrix, cmap=pylab.cm.gray)
        # Clear tick marks
        axes.set_xticks([])
        axes.set_yticks([])
        # Save image
        imageFile = StringIO.StringIO()
        pylab.savefig(imageFile, format='png')
        imageFile.seek(0)
        # Append
        images.append(Image.open(imageFile))
    # Return
    return images
 def setFontSize(self, event):
     dlg = wx.TextEntryDialog(self, "New font size", "Font Size")
     s = mpl.rc_params()['font.size']
     dlg.SetValue(str(s))
     if dlg.ShowModal() == wx.ID_OK:
         s = float(dlg.GetValue())
         mpl.rcParams.update({'font.size': s})
         self.figure.canvas.draw()
     dlg.Destroy()
Esempio n. 5
0
def imwrite_to_workspace(img,
                         filename,
                         workspace_dir=WORKSPACE_DIR,
                         cmap=None,
                         **imsave_args):
    cmap = cmap if cmap is not None else matplotlib.rc_params()['image.cmap']
    plt.imsave(fname=os.path.join(workspace_dir, filename),
               arr=img,
               cmap=cmap,
               **imsave_args)
Esempio n. 6
0
 def __init__(self, style: dict[str, Any] = None, color: Optional[str] = None) -> None:
     style_ = self._default_style.copy()
     if style is not None:
         style_.update(style)
     if color is not None:
         style_["color"] = color
     if "color" not in style_:
         cycler = mpl.rc_params()["axes.prop_cycle"]
         color = cycler.by_key()["color"][StyledObject._idx]
         StyledObject._idx += 1
         if StyledObject._idx + 1 > len(cycler):
             StyledObject._idx = 0
         style_["color"] = color
     self.style = style_
def heatmap(data, method='pearson', camp='Blues', figsize=(10, 8)):
    """
    data: 整份数据
    method:默认为 pearson 系数
    camp:默认为:RdYlGn-红黄蓝;YlGnBu-黄绿蓝;Blues/Greens 也是不错的选择
    figsize: 默认为 10,8
    """
    # ## 消除斜对角颜色重复的色块

    font1 = {'family': 'Arial', 'size': 10}
    font2 = {'family': 'Arial', 'size': 8}

    mask = np.zeros_like(df.corr())
    mask[np.triu_indices_from(mask)] = True

    matplotlib.rcParams['agg.path.chunksize'] = 60000
    matplotlib.rcParams.update(matplotlib.rc_params())
    plt.rcParams['font.family'] = 'Arial'
    plt.rcParams['font.size'] = '10'
    plt.rcParams['figure.figsize'] = (10, 10)
    # plt.xlim([0.0, 1.0])
    # plt.ylim([0.0, 1.0])
    # plt.xticks(font=font2)
    # plt.yticks(font=font2)

    plt.figure(figsize=figsize, dpi=80)
    sns.heatmap(data.corr(method=method),
                xticklabels=data.corr(method=method).columns,
                yticklabels=data.corr(method=method).columns,
                cmap=camp,
                center=0,
                annot=True,
                mask=mask)

    plt.savefig(r'D:\research paper\paper\论文\DL实验记录\统计图\线性图.jpeg', dpi=1000)

    plt.show()
Esempio n. 8
0
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.dates as mpldates
from cycler import cycler

import click
from pathlib import Path

# Modern Pandas requires this
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

# Requires Python 3.6+ for format strings

# Add fill variations for large numbers of colors
color_cycler = mpl.rc_params()['axes.prop_cycle']
hatch_cycler = cycler(hatch=['', '///', '+++', '***'])
prop_cycle = hatch_cycler * color_cycler


# This is a workaround because the pandas stacked plot does not use dates, just integers. Grrr!
def stacked_plot(df, ax=None, **kargs):
    old = None
    current_prop = prop_cycle()
    for column in df:
        current = df[column]
        if old is None:
            bottom = current * 0
        else:
            bottom = df.cumsum(axis=1)[old]
        art = ax.bar(df.index,
Esempio n. 9
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)

        # Init 0 for draw...
        plt.rcParams['agg.path.chunksize'] = 0
        matplotlib.rcParams['agg.path.chunksize'] = 0
        matplotlib.rcParams.update(matplotlib.rc_params())

        self.dpi = 100
        self.signalframe = self.widget_Signal_TimeDomain
        self.figure = Figure((11.3, 6.3), dpi=self.dpi)
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setParent(self.signalframe)
        self.axes = self.figure.add_subplot(111)
        #self.axes.set_title('Signal')
        self.axes.set_xlabel('Time(μs)')
        self.axes.set_ylabel('Voltage')
        #plt.subplots_adjust(left=0.2, bottom=0.2, right=0.8, top=0.8, hspace=0.2, wspace=0.3)

        timespan = self.getRecordLength() * 1024 / self.getSampleRate(
        )  # in us
        x = np.linspace(0, timespan, self.getRecordLength() * 1024)
        normalLimY = self.getVoltageScale() * 10
        self.axes.set_ylim(-normalLimY / 2 + self.getOffset(),
                           normalLimY / 2 + self.getOffset())
        ymajorLocator = MultipleLocator(self.getVoltageScale())
        yminorLocator = MultipleLocator(self.getVoltageScale() / 2)
        self.axes.yaxis.set_major_locator(ymajorLocator)
        self.axes.yaxis.set_minor_locator(yminorLocator)
        self.axes.grid(True)

        self.figure.tight_layout()  # Adjust spaces
        #self.NavToolbar = NavigationToolbar(self.canvas, self.signalframe)
        #self.addToolBar(QtCore.Qt.RightToolBarArea, NavigationToolbar(self.canvas, self.signalframe))
        self.toolbar = NavigationToolbar(self.canvas, self.signalframe)
        self.toolbar.hide()

        # Button slots
        self.pushButton_Home.clicked.connect(self.home)
        self.pushButton_Back.clicked.connect(self.back)
        self.pushButton_Forward.clicked.connect(self.forward)
        self.pushButton_Pan.clicked.connect(self.pan)
        self.pushButton_Zoom.clicked.connect(self.zoom)
        self.pushButton_SavePic.clicked.connect(self.savepic)

        # Init Socket
        self.udpSocketClient = UDPSocketClient()

        # Init FrameNum
        self.checkBox_FrameMode.setEnabled(True)
        self.frameNum = self.getFrameNumber()
        # 0x4
        self.sendCmdFramNum(self.frameNum)

        # Init Length 0x8
        self.comboBox_RecordLength.setCurrentIndex(6)  # 64k
        # Set RecordLength
        self.sendCmdRecordLength(self.getRecordLength() *
                                 self.getFrameNumber())

        #Init Trigger 0x2, bit2
        self.comboBox_TriggerDomain.setCurrentIndex(1)  # External
        self.sendCmdTriggerType(self.getTriggerType())

        # Reset PFGA to read to capture data
        if (self.getTriggerType() == 0):
            self.sendCmdWRREG(0x2, 0x20)
            self.sendCmdWRREG(0x2, 0x28)
        else:
            self.sendCmdWRREG(0xa, 0x0)
            self.sendCmdWRREG(0x2, 0x2c)
            self.sendCmdWRREG(0x2, 0x2d)

        # Read sampleRate
        value = self.readCmdSampleRate()
        if value > 5:
            value = 0
        self.comboBox_SampleRate.setCurrentIndex(value)

        # The last data
        self.lastChAData = []
        self.lastChBData = []

        self.realTimeThread = None
        self.externalTriggerThread = None
plt.close()
#######################################

#######################################
### Technical details of how rc parameters are implemented (extended read)
# http://matplotlib.org/api/matplotlib_configuration_api.html?highlight=rcparams#matplotlib.rcParams

### RcParams is a class in matplotlib package.
# It implements a dictionary object that holds all default values for plotting with matplotlib.
# rcParams is an object instance of RcParams in matplotlib package.
# It implements a dictionary object that stores default matplotlib parameters.

### rc_params() is a function in matplotlib package.
# It returns a matplotlib.RcParams() instance from the default matplotlib rc file.
import matplotlib as mpl
print mpl.rc_params()
# or print the dictionary object:
print mpl.rcParams
# you can either access it through matplotlib itself, or through matplotlib.PyPlot
print plt.rcParams

### plt.rc() is a function in matplotlib package.
# It sets the current rc parameters.
mpl.rc('lines', linewidth=2, color='r')
plt.plot(range(5), range(5))

# rc() sets multiple parameters at once. The code above is equivalent to:
plt.rcParams['lines.linewidth'] = 2
plt.rcParams['lines.color'] = 'r'
#######################################
Esempio n. 11
0
# Conditional imports and mpl customizations (provided mpl defaults have not been
# changed by user)
if __plt__:
    import matplotlib.pyplot as plt
    import matplotlib.style as mplstyle
    import matplotlib as mpl
    from matplotlib import colors

    # Syncopy default plotting settings
    spyMplRc = {"figure.dpi": 100}

    # Check if we're running w/mpl's default settings: if user either changed
    # existing setting or appended new ones (e.g., color definitions), abort
    changeMplConf = True
    rcDefaults = mpl.rc_params()
    rcKeys = rcDefaults.keys()
    with warnings.catch_warnings(
    ):  # examples.directory was deprecated in Matplotlib 3.0, silence the warning
        warnings.simplefilter("ignore")
        rcParams = dict(mpl.rcParams)
        rcParams.pop("examples.directory", None)
    rcParams.pop("backend")
    rcParams.pop("interactive")
    for key, value in rcParams.items():
        if key not in rcKeys:
            changeMplConf = False
            break
        if rcDefaults[key] != value:
            changeMplConf = False
            break
Esempio n. 12
0
"""

import numpy as np
import matplotlib as mpl  # 导入matplotlib库
import matplotlib.pyplot as plt  # 主要的绘图子库
'''
# matplotlib的所有配置保存在下面的字典中,修改字典对应的值即为修改配置
print(mpl.rcParams)
print(mpl.get_configdir())   # 获取配置文件夹
print(mpl.matplotlib_fname())   # 获取当前使用的配置文件路径

mpl.rcParams['font.family'] = 'SimHei'   # 修改字体支持中文,解决中文乱码
mpl.rcParams['backend'] = 'TkAgg'   # 修改后端,解决Qt5平台错误
mpl.rcParams['axes.unicode_minus'] = False # 解决负号显示为方块
'''
'''
上述的配置只在当前执行文件中生效,可以直接在配置文件修改,永久生效
Anaconda3\Lib\site-packages\matplotlib\mpl-data\matplotlibrc   # matplotlib默认配置文件,修改配置后永久有效
> font.family : SimHei   # 解决中文乱码
> backend : TkAgg   # 解决 Qt5 平台报错
> axes.unicode_minus : False   # 解决负号是方块
mpl.rc_params()   # 重新读取配置,以字典形式返回
'''
figure = plt.figure()  # 创建画布
'''
# 创建坐标系,参数表示画布中可以放置2行3列坐标系,即6个坐标系,当前选用的是第1个
axes_plot = figure.add_subplot(2, 3, 1) # 可缩写为axes_plot = figure.add_subplot(231)
axes_plot.plot([1,2,3,4], [1,2,3,4])
'''
'''
# 直接使用plt及逆行绘制图形
Esempio n. 13
0
import matplotlib
import os
import pylab
# 获得用户配置路径
print("the user config is ", matplotlib.get_configdir())
# 获得当前配置文件路径
print("the current config is ", matplotlib.matplotlib_fname())
# 获得当前文件路径
print(os.getcwd())
# rc_params返回一个配置字典
print("the return of rc_params are \n", matplotlib.rc_params())
# 使用matplotlib时会自动调用rc_params,并将返回的配置字典保存在rcparams中
print("the rcparams are \n", matplotlib.rcParams)
# 修改配置(绘制的线带有点标识符)
pylab.figure()
matplotlib.rcParams["lines.marker"] = 'o'
pylab.plot([1, 2, 3])
# 使用rc简便地修改配置
pylab.figure()
# 这里设置颜色失败,不知道是什么情况
matplotlib.rc("lines", color="red", marker="x", linewidth=2)
pylab.plot([1, 2, 3])
# 恢复缺省配置
pylab.figure()
matplotlib.rcdefaults()
pylab.plot([1, 2, 3])
pylab.legend()
pylab.show()
Esempio n. 14
0
     'patch.antialiased': True,
     'patch.edgecolor': '#EEEEEE',
     'patch.facecolor': '#348ABD',
     'patch.linewidth': 0.5,
     'toolbar': 'toolbar2',
     'xtick.color': '#555555',
     'xtick.direction': 'in',
     'xtick.major.pad': 6.0,
     'xtick.major.size': 0.0,
     'xtick.minor.pad': 6.0,
     'xtick.minor.size': 0.0,
     'ytick.color': '#555555',
     'ytick.direction': 'in',
     'ytick.major.pad': 6.0,
     'ytick.major.size': 0.0,
     'ytick.minor.pad': 6.0,
     'ytick.minor.size': 0.0
}

import numpy as np
import matplotlib as mpl
import matplotlib.pylab as pl

mpl.rc_params().update(mpl_stylesheet)


xs, ys = np.random.uniform(0,1,size=(2,30))
pl.scatter(xs, ys)

pl.show()
Esempio n. 15
0
#
# You should have received a copy of the GNU General Public License
# along with GWpy.  If not, see <http://www.gnu.org/licenses/>.

"""Custom default figure configuration
"""

from matplotlib import (rcParams, rc_params, RcParams,
                        __version__ as mpl_version)
from matplotlib.figure import SubplotParams

from . import tex
from ..utils.env import bool_env

# record matplotlib's original rcParams
MPL_RCPARAMS = rc_params()

__author__ = "Duncan Macleod <*****@*****.**>"

# -- custom rc ----------------------------------------------------------------

# set default params
GWPY_RCPARAMS = RcParams(**{
    # axes boundary colours
    'axes.edgecolor': 'gray',
    # grid
    'axes.grid': True,
    'axes.axisbelow': False,
    'grid.linewidth': .5,
    # ticks
    'axes.formatter.limits': (-3, 4),
Esempio n. 16
0
    'xtick.major.size':
    0.0,
    'xtick.minor.pad':
    6.0,
    'xtick.minor.size':
    0.0,
    'ytick.color':
    '#555555',
    'ytick.direction':
    'in',
    'ytick.major.pad':
    6.0,
    'ytick.major.size':
    0.0,
    'ytick.minor.pad':
    6.0,
    'ytick.minor.size':
    0.0
}

import numpy as np
import matplotlib as mpl
import matplotlib.pylab as pl

mpl.rc_params().update(mpl_stylesheet)

xs, ys = np.random.uniform(0, 1, size=(2, 30))
pl.scatter(xs, ys)

pl.show()
Esempio n. 17
0
              'figure.facecolor': '#161616',
              'savefig.edgecolor': 'black',
              'savefig.facecolor': 'black',
              }

Themes = OrderedDict()

for tname in ('light', 'dark', 'matplotlib', 'seaborn', 'ggplot', 'bmh',
              'fivethirtyeight', 'grayscale', 'dark_background',
              'tableau-colorblind10', 'seaborn-bright',
              'seaborn-colorblind', 'seaborn-dark', 'seaborn-darkgrid',
              'seaborn-dark-palette', 'seaborn-deep', 'seaborn-notebook',
              'seaborn-muted', 'seaborn-pastel', 'seaborn-paper',
              'seaborn-poster', 'seaborn-talk', 'seaborn-ticks',
              'seaborn-white', 'seaborn-whitegrid', 'Solarize_Light2'):
    theme = rc_params()
    theme['backend'] = 'WXAgg'
    if tname == 'matplotlib':
        pass
    elif tname == 'light':
        theme.update(light_theme)
    elif tname == 'dark':
        theme.update(light_theme)
        theme.update(dark_theme)
    elif tname in matplotlib.style.library:
        if tname.startswith('seaborn-'):
            theme.update(matplotlib.style.library['seaborn'])
        theme.update(matplotlib.style.library[tname])
    Themes[tname.lower()] = theme

def bool_ifnotNone(val, default):
Esempio n. 18
0
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GWpy.  If not, see <http://www.gnu.org/licenses/>.

"""This module provides plotting utilities for visualising GW data

The standard data types (`TimeSeries`, `Table`, `DataQualityFlag`, ...) can
all be easily visualised using the relevant plotting objects, with
many configurable parameters both interactive, and in saving to disk.
"""

from matplotlib import (rcParams, rc_params, pyplot)

DEFAULT_RCPARAMS = rc_params()

__author__ = "Duncan Macleod <*****@*****.**>"

from .tex import (USE_TEX, MACROS)
from .gps import *
from .log import *

from .core import *
from .timeseries import *
from .spectrogram import *
from .frequencyseries import *
from .segments import *
from .filter import *
from .table import *
from .histogram import *
Esempio n. 19
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 26 20:45:41 2019

@author: xsxsz
"""

import matplotlib
import matplotlib.pyplot as plt

print(matplotlib.get_backend())
print('-------------------')
print(matplotlib.get_configdir())
print('-------------------')
print(matplotlib.get_cachedir())
print('-------------------')
print(matplotlib.get_data_path())
print('-------------------')
print(matplotlib.matplotlib_fname())
print('-------------------')
print(matplotlib.rc_params())
print('-------------------')
Esempio n. 20
0
from networkx.readwrite import json_graph
import json

import sys

print "nx version : " + nx.__version__

###############################################
import matplotlib
print matplotlib.rc.func_globals['defaultParams']
matplotlib.get_backend()
#matplotlib.rcdefaults() # set params back to defaults.
#print matplotlib.matplotlib_fname()
#matplotlib.rcsetup
dict_of_rcParam = matplotlib.rc_params()

img_background = 'achzive_1.jpg'
img_background = 'cartoon-funny-dinosaur.jpg'
bkImg = Image.open(img_background)
#bkImg.show() opens system image viewer
plt.imshow(bkImg)

plt.close()
###############################################

if __name__ == '__main__':
    doc = minidom.parse("./example.xml")
    output_rel_path = "../runtime_outputs/"
else:
    doc = minidom.parse("./specific_files/example.xml")
# Homework 3 Model Comparisons
# Sean Thatcher
# Environmental Informatics
# Instructor Dr. Rodger Wang

# Install packages

import matplotlib  # Data Visualizations
import matplotlib.pyplot as plt
matplotlib.rc_params().update({'font.size': 22})

# Data being used
# Values being hard coded because there is only 1 model value
# and 1 observation value from the gage at each stage.
# The model values were computed in a spreadsheet from model outputs.
# The values and calculations can be found in the HAND Data for Stations spreadshet.
# Values from gauges were obtained from the USGS and a stage of the same/similar
# stage event modeled were selected for comparison.

# Green Brook at Burnt Mills NJ
# Station number 1403400

green_brook_1m_gauge = 0.427078125
green_brook_1m_model = 2.030675754
green_brook_3m_gauge = 91.414
green_brook_3m_model = 37.71595379

# Green Brook at Seeley Mills NJ
# Station number 1401650

pike_run_3m_gauge = 2.126028046
# 5. 显示图形
plt.show()

# !!! 配置
print(mpl.rcParams)  # 获取全部配置
print(mpl.rcParams['font.family'])  # 获取字体
#mpl.rcParams['font.family'] = 'SimHei' # 设置字体

print(mpl.rcParams['backend'])
#mpl.rcParams['backend'] = 'TkAgg' # Qt5

print(mpl.rcParams['axes.unicode_minus'])
#mpl.rcParams['axes.unicode_minus'] = False

print(mpl.matplotlib_fname())  # 获取配置文件路径
mpl.rc_params()  # 重新加载配置

# 折线图
# 创建画布
fig = plt.figure(figsize=(8, 6))
# 创建一个坐标系
axes1 = fig.add_subplot(1, 1, 1)
# 绘制图形
plot_x = np.linspace(-5, 5, 20)
plot_y = plot_x**2
#plot_x_2 = np.linspace(-5, 5, 100)
plot_y_2 = plot_x * 2
axes1.plot(plot_x, plot_y, '--c', label='y')
axes1.plot(plot_x, plot_y_2, label='y=x*2')
axes1.set_title('曲线')  # 设置标题
axes1.set_xlabel('x 轴')  # 设置x轴名称
Esempio n. 23
0
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GWpy.  If not, see <http://www.gnu.org/licenses/>.
"""This module provides plotting utilities for visualising GW data

The standard data types (`TimeSeries`, `Table`, `DataQualityFlag`, ...) can
all be easily visualised using the relevant plotting objects, with
many configurable parameters both interactive, and in saving to disk.
"""

from matplotlib import (rcParams, rc_params, pyplot)

DEFAULT_RCPARAMS = rc_params()

__author__ = "Duncan Macleod <*****@*****.**>"

from .tex import (USE_TEX, MACROS)
from .gps import *
from .log import *

from .core import *
from .timeseries import *
from .spectrogram import *
from .frequencyseries import *
from .segments import *
from .filter import *
from .table import *
from .histogram import *
Esempio n. 24
0
from tqdm import tqdm  # smart progress bar
from PIL import Image
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import rc_params
import pandas as pd
import numpy as np

#skimage features and filters
from skimage.feature import daisy
from skimage.feature import hog
from skimage.color import rgb2gray
from skimage.exposure import equalize_hist

# get our styles
mpl_default = rc_params()

import seaborn as sns

# for ipython notebook %matplotlib inline
plt.rcParams = mpl_default

# BEES colormap! Black -> Yellow
CMAP = [(0, 0, 0), (22, 0, 0), (43, 0, 0), (77, 14, 0), (149, 68, 0),
        (220, 123, 0), (255, 165, 0), (255, 192, 0), (255, 220, 0),
        (255, 235, 0), (255, 245, 0), (255, 255, 0)]

bees_cm = mpl.colors.ListedColormap(np.array(CMAP) / 255.)

# load the labels using pandas
labels = pd.read_csv("data/train_labels.csv", index_col=0)
Esempio n. 25
0
from tqdm import tqdm # smart progress bar
from PIL import Image
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import rc_params
import pandas as pd
import numpy as np

#skimage features and filters
from skimage.feature import daisy
from skimage.feature import hog
from skimage.color import rgb2gray
from skimage.exposure import equalize_hist
 
# get our styles
mpl_default = rc_params()
 
import seaborn as sns
 
# for ipython notebook %matplotlib inline
plt.rcParams = mpl_default

# BEES colormap! Black -> Yellow
CMAP = [(0,0,0),
        (22,0,0),
        (43,0,0),
        (77,14,0),
        (149,68,0),
        (220,123,0),
        (255,165,0),
        (255,192,0),
Esempio n. 26
0
ax2 = plt.subplot2grid((3, 3), (0, 2), rowspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 0), rowspan=2)
ax4 = plt.subplot2grid((3, 3), (2, 1), colspan=2)
ax5 = plt.subplot2grid((3, 3), (1, 1))
plt.show()

# 配置文件   可以使用多个matplotlibrc配置文件,顺序靠前的配置文件会被优先采用
# 搜索顺序如下:当前路径-->用户配置路径(通常在.matplotlib目录下)-->系统配置路径
# 获取用户配置路径
from os import path
import matplotlib
# 获取当前配置路径
current_path = path.abspath(matplotlib.matplotlib_fname())
print(current_path)
# 读取配置文件配置内容, 本质上是一个字典
print(matplotlib.rc_params())

# 修改配置信息
matplotlib.rc("lines", marker="x", lw=2, color="red")

# 配置恢复默认
matplotlib.rcdefaults()

# 手工修改配置后,重新载入最新配置
matplotlib.rcParams.update(matplotlib.rc_params())

# 获取用户配置路径
user_path = path.abspath(matplotlib.get_configdir())
print(user_path)

# 样式切换  matplotlib.style
Esempio n. 27
0
    for (n, e), j in zip(exps, jobs):
        e.save_serialized_parameters(j.config)
elif ACTION == 'run':
    pool.run()
    if LAUNCHER == 'process' or args.watch:
        print_refreshed_stats()
elif ACTION == 'status':
    if args.watch:
        print_refreshed_stats()
    else:
        print_stats()
elif ACTION == 'plot':
    import matplotlib
    # Set matplotlib config
    if args.plot_config is None:
        plot_params = matplotlib.rc_params()
        plot_params.update(DEFAULT_PLOT_PARAMS)
    else:
        plot_params = matplotlib.rc_params_from_file(args.plot_config,
                                                     fail_on_error=True)
    plot_params['interactive'] = not args.no_plot
    matplotlib.rcParams = plot_params
    assert(plot_params == matplotlib.rcParams)
    assert(plot_params is matplotlib.rcParams)
    from multimodal.plots import (plot_2k_graphs, plot_boxes,
                                  plot_boxes_by_feats, plot_boxes_all_mods)
    LOGGERS_2 = collect_results()
    LOGGERS_3 = collect_results3()
    LOGGERS_IMAGE = collect_results_image()
    plot_params = DEFAULT_PLOT_PARAMS
    fig_2k = plot_2k_graphs([LOGGERS_2, LOGGERS_3], Ks,
Esempio n. 28
0
import matplotlib

GUI_RC_PARAMS = matplotlib.rc_params()
GUI_RC_PARAMS.update({
    'axes.titlesize': 'medium',
    'figure.autolayout': True,
    'legend.fontsize': 'small',
    'legend.framealpha': 0.5,
    'lines.linewidth': 1.0,
})
Esempio n. 29
0
# -*- coding: utf-8 -*-
"""
Created on Sun Jun  9 17:56:50 2019

@author: user
"""
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
print(mpl.rc_params())  # shows the default parameters
# This update will only be in this program and printing the mpl.rc_params() will not show the updated values
mpl.rcParams.update({
    'font.size': 18,
    'font.family': 'STIXGeneral',
    'mathtext.fontset': 'stix'
})
# To Go back to the default settings
#mpl.rcParams.update(mpl.rcParamsDefault)
# Print the plot atyles available
print(plt.style.available)


def plotsincosin(style='ggplot'):
    plt.style.use(style)
    plt.figure(figsize=(7, 4), dpi=80)
    x = np.linspace(0, 2 * np.pi, 1000)
    plt.plot(x, np.sin(x))
    plt.plot(x, np.cos(x))
    plt.xticks(
        ticks=np.arange(0, 440 / 57.2985, 90 / 57.2985),
        labels=[r'$0$', r'$90$', r'$\pi$', r'$\frac{3\pi}{2}$', r'$2\pi$'])
Esempio n. 30
0
def plot_3d(series, colormap_callable=plt.cm.viridis, include_colorbar=False):
    """Create a 3d-barchart axes for a given 2-level-multi-index series.

    Return a 3d axes object given a series with a multiindex with 2
    categorical levels.

    Arguments:
        series (pandas.Series): the 2-level-index series to generate the plot.
        colormap_callable (matplotlib.colors.ListedColormap): Colormap object
        generated from a list of colors.
        include_colorbar (bool): True to include a colorbar.

    Returns:
        matplotlib.axes.Axes: the 3d axis object.

    Examples:
        >>> import itertools
        >>> import pandas as pd
        >>> fig = plt.figure()
        >>> s_index = pd.MultiIndex.from_tuples(                              \
            tuple(itertools.product(range(6), list('abc'))),                  \
        names=('x1', 'x2'))
        >>> s = pd.Series(data=np.arange(18), index=s_index)
        >>> ax = plot_3d(s, include_colorbar=True)
        >>> fig.tight_layout()
        >>> fig.savefig('/tmp/{0}.png'.format('plot3d'), dpi=500)

    """
    # Create a copy of the list to avoid changing the original.
    series = series.copy(deep=True)
    series.sort_values(inplace=True, ascending=False)
    # Set constants.
    # Some groupby objects will produce a dataframe. Not nice going over duck
    # typing but oh well...
    # If it is a dataframe with one column then transform it to series.
    if isinstance(series, pd.DataFrame) and series.shape[1] == 1:
        series = series.ix[:, 0]

    # Error handling phase.
    # Track if index has correct shape.
    if len(series.index.levshape) != 2:
        raise ValueError('The index level shape should '
                         'be 2 and it is {}.'.format(series.index.levshape))
    # Check for duplicate indexes.
    if series.index.duplicated().sum():
        series = series.groupby(level=series.index.names).sum()
        if series.index.duplicated().sum():
            raise ValueError('series has duplicate values.')

    # Handling the index of the received series.
    level1_index, level2_index = tuple(zip(*series.index.get_values()))
    level1_index = sorted(set(level1_index))
    level2_index = sorted(set(level2_index))

    # Populate the series with all index combinations, even if they are zero.
    all_index_combinations = tuple(
        itertools.product(level1_index, level2_index))
    index_names = series.index.names
    new_index = pd.MultiIndex.from_tuples(all_index_combinations,
                                          names=index_names)
    all_values_series = pd.Series(0, index=new_index, name=series.name)
    series = (series + all_values_series).fillna(0)

    # Generate the z values
    z_list = []
    for _, group in series.groupby(level=1):
        z_list.append(group)
    z_list = np.hstack(z_list).ravel()
    z = z_list
    del z_list

    # Starts manipulating the axes
    fig = plt.gcf()
    ax = fig.add_subplot(111, projection='3d')

    # Create the axis and their labels
    xlabels = series.index.get_level_values(index_names[0]).unique().tolist()
    ylabels = series.index.get_level_values(index_names[1]).unique().tolist()
    xlabels = [
        ''.join(list(filter(str.isalnum, str(value)))) for value in xlabels
    ]
    ylabels = [
        ''.join(list(filter(str.isalnum, str(value)))) for value in ylabels
    ]
    x = np.arange(len(xlabels))
    y = np.arange(len(ylabels))
    xlabels = [z.title() for z in xlabels]
    ylabels = [z.title() for z in ylabels]
    # Adjust tick posistions and labels.
    ax.w_xaxis.set_ticks(x + 0.5 / 2.)
    ax.w_yaxis.set_ticks(y + 0.5 / 2.)
    ax.w_yaxis.set_ticklabels(ylabels)

    # Color.
    pp_color_values = sklearn.preprocessing.minmax_scale(z)
    colormap = colormap_callable(pp_color_values)

    # Create the 3d plot.
    x_mesh, y_mesh = np.meshgrid(x, y, copy=False)
    ax.bar3d(x_mesh.ravel(),
             y_mesh.ravel(),
             z * 0,
             dx=0.5,
             dy=0.5,
             dz=z,
             color=colormap)

    # Set convenient z limits.
    # From z ticks make it include all extreme values in excess of 0.5 tick.
    z_min = z.min()
    z_max = z.max()
    z_ticks = ax.get_zticks()
    z_stride = z_ticks[1] - z_ticks[0]
    z_min_lim = z_min - 0.5 * z_stride
    z_max_lim = z_max + 0.5 * z_stride
    if 0 < z_min_lim:
        z_min_lim = 0
    elif 0 > z_max_lim:
        z_max_lim = 0
    ax.set_zlim3d(z_min_lim, z_max_lim)

    if include_colorbar:
        scalar_mappable = plt.cm.ScalarMappable(cmap=colormap_callable)
        scalar_mappable.set_array([min(z), max(z)])
        scalar_mappable.set_clim(vmin=min(z), vmax=max(z))
        ticks = np.linspace(z_min, z_max, 5)
        colorbar = fig.colorbar(scalar_mappable, drawedges=True, ticks=ticks)
        # Add border to the colorbar.
        colorbar.outline.set_visible(True)
        colorbar.outline.set_edgecolor('black')
        mpl_params = matplotlib.rc_params()
        colorbar.outline.set_linewidth(mpl_params['lines.linewidth'])
        # Add ticks to the colorbar.
        colorbar.ax.yaxis.set_tick_params(
            width=mpl_params['ytick.major.width'],
            size=mpl_params['ytick.major.size'])
    return ax
Esempio n. 31
0
from networkx.readwrite import json_graph
import json

print ("nx version : " + nx.__version__)


###############################################
matplotlib.use('WXAgg')
import matplotlib
#print (matplotlib.rc.func_globals['defaultParams'])
print (matplotlib.rc.__globals__['defaultParams'])
matplotlib.get_backend()
#matplotlib.rcdefaults() # set params back to defaults.
print (matplotlib.matplotlib_fname())
#matplotlib.rcsetup
matplotlib.rc_params()
###############################################

if __name__=='__main__':
    doc = minidom.parse("./example.xml")
    output_rel_path = "./runtime_outputs/"
else:
    doc = minidom.parse("./specific_files/example.xml")
    output_rel_path = "./runtime_outputs/"
draw_edges_labels=False#True

''' generate the graph '''

# code ref: https://networkx.github.io/documentation/networkx-1.10/reference/classes.multidigraph.html
G               = nx.MultiDiGraph(name="Simulated System Graph")
G_wVirtualEdges = nx.DiGraph(name="Graph with added virtual edges nodes")
Esempio n. 32
0
#
# You should have received a copy of the GNU General Public License
# along with GWpy.  If not, see <http://www.gnu.org/licenses/>.
"""Custom default figure configuration
"""

import os

from matplotlib import (rcParams, rc_params, __version__ as mpl_version)
from matplotlib.figure import SubplotParams

from . import tex
from .colors import DEFAULT_COLORS

# record matplotlib's original rcParams
MPL_RCPARAMS = rc_params()

__author__ = "Duncan Macleod <*****@*****.**>"

# -- custom rc ----------------------------------------------------------------

# set default params
DEFAULT_PARAMS = {
    # axes boundary colours
    'axes.edgecolor': 'gray',
    # grid
    'axes.grid': True,
    'axes.axisbelow': False,
    'grid.linestyle': ':',
    'grid.linewidth': .5,
    # ticks
Esempio n. 33
0
matplotlib.get_backend()                    

class matplotlib.RcParams(*args, **kwargs)  # класс для хранения параметров
	copy()
	find_all(pattern)
	validate                                     # словарь с функциями валидации
matplotlib.rcParams                         # текущие параметры

matplotlib.rc_context(rc=None, fname=None)  # with rc_context(...) строим график

matplotlib.rc(group, **kwargs)              # устанавливает rc параметры
matplotlib.rc_file(fname)                   # устанавливает параметры из файла
matplotlib.rcdefaults()                     # устанавливает параметры по умолчанию
matplotlib.rc_file_defaults()               # устанавливает параметры из rc файла по умолчанию

matplotlib.rc_params(fail_on_error=False)   # возвращает параметры из rc файла по умолчанию
matplotlib.rc_params_from_file(fname, fail_on_error=False, use_default_template=True) # 
matplotlib.matplotlib_fname()               # путь к файлу с конфигами

matplotlib.interactive(b)                   # устанавливает интерактивность
matplotlib.is_interactive()                 # проверяет интерактивность

####################  module style
import matplotlib.style
matplotlib.style.context(style, after_reset=False)
matplotlib.style.reload_library()
matplotlib.style.use(style)
matplotlib.style.library                    # словарь доступных стилей
matplotlib.style.available                  # список доступных стилей

Esempio n. 34
0
 def test_plot_matplotlib_rc_restore(self, maps_release_only):
     rcparams = matplotlib.rc_params()
     map_ = maps_release_only.getMap('emline_gflux', channel='ha_6564')
     fig, ax = mapplot.plot(dapmap=map_)
     assert rcparams == matplotlib.rc_params()
Esempio n. 35
0
d_colors = {
    "1": "darksalmon",
    "2": "royalblue",
    "3": "mediumpurple",
    "4": "green",
    "5": "tan",
    "6": "brown",
    "7": "pink",
    "8": "olive",
    "9": "peru",
    "10": "orange",
    "11": "darkkhaki",
    "12": "cadetblue",
    "13": "crimson",
    "14": "thistle"
}

# Optimal Bandwidths
bw = np.array([1577.681, 1167.16, 30.549])
bw_stkde = np.array([
    7859.14550575 / 10,
    10910.84908688 / 10,
    24.38113667
])

if __name__ == '__main__':
    import matplotlib as mpl

    mpl.rcParams.update(rc)
    print(mpl.rc_params())