Ejemplo n.º 1
0
def group_pieChart(saveName, chartObj):
    data = pd.Series(chartObj)
    #print(data)
    myfont = FontProperties(fname=fname, size=14)
    sns.set(font=myfont.get_name())

    plt.rcParams['figure.figsize'] = (10.0, 8.0)  #调整图片大小

    lbs = data.index
    explodes = [0.1 if i == '其他' else 0 for i in lbs]
    plt.pie(data,
            explode=explodes,
            labels=lbs,
            autopct="%1.1f%%",
            colors=sns.color_palette("muted"),
            startangle=90,
            pctdistance=0.6,
            textprops={
                'fontsize': 14,
                'color': 'black'
            })
    plt.axis('equal')  # 设置x,y轴刻度一致,以使饼图成为圆形。
    # plt.title(saveName,fontproperties=myfont)
    plt.savefig('./images/' + saveName + '.jpg')
    plt.show()
Ejemplo n.º 2
0
def show_result():
    newspred = load_result('news2017_pred.txt')
    newsgold = load_result('news2017_gold.txt')

    weibopred = load_result('weibo_pred.txt')
    weibogold = load_result('weibo_gold.txt')

    sougoupred = load_result('sougou_pred.txt')
    sougougold = load_result('sougou_gold.txt')

    maxlen = max([
        max([max(len(s1), len(s2)) for s1, s2 in zip(newspred, newsgold)]),
        max([max(len(s1), len(s2)) for s1, s2 in zip(weibopred, weibogold)]),
        max([max(len(s1), len(s2)) for s1, s2 in zip(sougoupred, sougougold)])
    ]) + 1
    weiboresult = analysis(weibopred, weibogold, maxlen)
    newsresult = analysis(newspred, newsgold, maxlen)
    sougouresult = analysis(sougoupred, sougougold, maxlen)

    myfont = FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf', size=14)
    sns.set(font=myfont.get_name())

    data = pd.DataFrame(data={
        'news2017': newsresult,
        'weibo': weiboresult,
        'sougou': sougouresult
    },
                        index=[i + 1 for i in range(maxlen)])

    sns.lineplot(data=data, palette='tab10', linewidth=2.5)
    plt.title('各测试集上不同长度词/句的完全正确率')
    plt.show()
Ejemplo n.º 3
0
    def __plot(self, xname, group, agebins=[]):
        class_cols = [Columns.Date]
        if xname != Columns.Age:
            class_cols.append(xname)
        else:
            age_cuts = pd.cut(self.__original_data['AGE'],
                              bins=[int(a) for a in agebins.split(',')],
                              right=False)
            class_cols.append(age_cuts)

        if group != Columns.Age:
            class_cols.append(group)
        else:
            age_cuts = pd.cut(self.__original_data['AGE'],
                              bins=[int(a) for a in agebins.split(',')],
                              right=False)
            class_cols.append(age_cuts)

        vol = VolumeAnalyzer.get_outpatient_volume(self.__original_data,
                                                   class_cols)
        myfont = FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf', size=14)
        sns.set(font=myfont.get_name(), style='white')

        g = sns.boxplot(
            x=xname,
            y=Columns.OutpatientVol,
            hue=group,
            data=vol,
        )
        plt.xticks(rotation=45)
        plt.show()
Ejemplo n.º 4
0
    def initialize_mpl_fonts(self):

        from matplotlib.font_manager import _rebuild; _rebuild()

        fp = FontProperties(fname=self.font_path)

        rcParams['font.serif']  = fp.get_name()
        rcParams['font.family'] = 'serif'
Ejemplo n.º 5
0
def plot(words,values,head):
    pdf=pd.DataFrame({"key":words,
                      "value":values})
    zhfont = FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf', size=14)
    plt.figure(figsize=[14,20])
    sns.set(font=zhfont.get_name())
    sns.barplot("key", "value", palette="RdBu_r", data=pdf.head(head))
    plt.show()
Ejemplo n.º 6
0
def seaborn_set(style="husl"):
    '''
    具体解决seaborn不显示中文的问题, 并且设置seaborn的分隔色彩
    :param style: (String) husl, hls, Paired...
                    具体见 https://seaborn.pydata.org/tutorial/color_palettes.html
    '''
    myfont = FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf', size=14)
    sns.set(font=myfont.get_name(), palette=style)
Ejemplo n.º 7
0
 def __init__(self):
     self.drawchart = DrawChart()
     self.wight = 12  # 设置画布宽度
     self.height = 6.75  # 设置画面高度
     self.dpi = 300  # 设置输出图片的dpi
     myfont = FontProperties(
         fname=r'C:\Windows\Fonts\msyhbd.ttc')  # 设置字体为微软雅黑
     sns.set(font=myfont.get_name(), style='white',
             palette="deep")  # 设置图形背景和调色板主题
Ejemplo n.º 8
0
def find_times_font(bold=False, italic=False):
    fonts = findSystemFonts()
    for fontpath in fonts:
        fprop = FontProperties(fname=fontpath)
        name = fprop.get_name()
        name_matched = 'Times New Roman' in name
        pname = os.path.splitext(os.path.basename(fontpath))[0]
        style_matched = ((not bold) or (bold and (pname.endswith('Bold') or (pname.lower() == pname and pname.endswith('bd'))))) and \
                        ((not italic) or (italic and (pname.endswith('Italic') or (pname.lower() == pname and pname.endswith('i')))))
        if name_matched and style_matched:
            return fprop
    return None
Ejemplo n.º 9
0
    def findFont(self, props):
        from matplotlib.font_manager import FontProperties, findfont

        # search for the best match
        font = FontProperties(fname=findfont(FontProperties(**props)))

        props = {
            'family': font.get_name(),
            'weight': font.get_weight(),
            'style': font.get_style(),
        }
        return props
Ejemplo n.º 10
0
	def findFont(self, props):
		from matplotlib.font_manager import FontProperties, findfont

		# search for the best match
		font = FontProperties( fname=findfont( FontProperties(**props) ) )

		props = {
			'family' : font.get_name(),
			'weight' : font.get_weight(),
			'style' : font.get_style(),
		}
		return props
Ejemplo n.º 11
0
def find_times_font(bold=False, italic=False):
    fonts = findSystemFonts()
    for fontpath in fonts:
        fprop = FontProperties(fname=fontpath)
        name = fprop.get_name()
        name_matched = 'Times New Roman' in name
        pname = os.path.splitext(os.path.basename(fontpath))[0]
        style_matched = ((not bold) or (bold and (pname.endswith('Bold') or (pname.lower() == pname and pname.endswith('bd'))))) and \
                        ((not italic) or (italic and (pname.endswith('Italic') or (pname.lower() == pname and pname.endswith('i')))))
        if name_matched and style_matched:
            return fprop
    return None
Ejemplo n.º 12
0
 def wordCloud(self, sample=20, xmin=-100, xmax=100, ymin=-100, ymax=100):
     if self.hasBuildRepresentation == False:
         print(
             "Error - no representation : call 'create2DDict' to build 2D representation."
         )
         return
     fig = plt.figure(figsize=(10, 8))
     fp = FontProperties(fname='./Osaka.ttc', size=10)
     rcParams['font.family'] = fp.get_name()
     for word in tqdm(np.random.choice(self.idict, sample)):
         point = self.dict2D[word]
         x = point[0]
         y = point[1]
         if x >= xmin and x <= xmax and y >= ymin and y <= ymax:
             plt.plot(x, y, 'bo')
             plt.text(x * (1 + 0.01), y * (1 + 0.01), word, fontsize=12)
     plt.xlim((xmin, xmax))
     plt.ylim((ymin, ymax))
     plt.show()
Ejemplo n.º 13
0
 def __init__(self, chart, crest_factor, rms_level, headroom, x_min, x_max,
              y_min, y_max, on_x_range_change):
     self.idx = 0
     self.__chart = chart
     self.__on_x_range_change = on_x_range_change
     self.__x_min = x_min
     self.__x_max = x_max
     self.__x_min.editingFinished.connect(self.__update_x_range)
     self.__x_max.editingFinished.connect(self.__update_x_range)
     self.__y_min = y_min
     self.__y_max = y_max
     self.__y_min.editingFinished.connect(self.__update_y_range)
     self.__y_max.editingFinished.connect(self.__update_y_range)
     self.__chart = chart
     label_font = QFont()
     fp = FontProperties()
     label_font.setPointSize(fp.get_size_in_points() * 0.7)
     label_font.setFamily(fp.get_name())
     for name in ['left', 'right', 'bottom', 'top']:
         self.__chart.getPlotItem().getAxis(name).setTickFont(label_font)
     self.__chart.getPlotItem().showGrid(x=True, y=True, alpha=0.5)
     self.__chart.getPlotItem().disableAutoRange()
     self.__chart.getPlotItem().setLimits(xMin=0.0,
                                          xMax=1.0,
                                          yMin=-1.0,
                                          yMax=1.0)
     self.__chart.getPlotItem().setXRange(0, 1, padding=0.0)
     self.__chart.getPlotItem().setYRange(-1, 1, padding=0.0)
     self.__chart.getPlotItem().setDownsampling(ds=True,
                                                auto=True,
                                                mode='peak')
     self.__chart.getPlotItem().layout.setContentsMargins(10, 20, 30, 20)
     self.__chart.getPlotItem().sigXRangeChanged.connect(
         self.__propagate_x_range)
     self.__chart.getPlotItem().sigYRangeChanged.connect(
         self.__propagate_y_range)
     self.__headroom = headroom
     self.__rms_level = rms_level
     self.__crest_factor = crest_factor
     self.__signal = None
     self.__curve = None
Ejemplo n.º 14
0
def group_histogram(saveName, index, chartObj, columns):
    # data = pd.Series(chartObj)
    bean = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
    data = pd.DataFrame(chartObj, columns=columns, index=index)
    myfont = FontProperties(fname=fname, size=14)
    sns.set(font=myfont.get_name())
    plt.rcParams['figure.figsize'] = (8.0, 6.0)  #调整图片大小
    plt.rcParams['axes.unicode_minus'] = False  #显示负号
    #pal_style = ['deep', 'muted', 'pastel', 'bright', 'dark','colorblind']
    sns.set_palette(sns.color_palette('bright'))  #设置调色板
    data.plot.bar(
        stacked=True,
        alpha=0.5,
    )

    plt.xticks(fontsize=16, rotation=0)  #设置x和y轴刻度值的字体大小;rotation规定水平排列刻度文字。
    plt.xticks(fontsize=16)  #设置x轴刻度值的字体大小
    plt.yticks(fontsize=16)  #设置y轴刻度值的字体大小

    plt.legend(fontsize=16)  #设置legend刻度值的字体大小
    plt.title("支付宝历年账单收支堆积柱状图", fontproperties='Simhei')
    plt.yticks(np.arange(0, 350000, 20000))  #设置y轴标签
    plt.savefig('./images/' + saveName + '.jpg')
    plt.show()
Ejemplo n.º 15
0
def plot_sns(text):
    ##list(set())去字符串重复
    li=list(set(text.split("/")))
    counte_phrase=[]
    #counte_phrase.append(["pharse","times"])
    counte_phrase_phrase=[]
    counte_phrase_times=[]
    for i in range(1000):
        ##验证过滤掉单个词。
        if(len(li[i]) != 1):
            counte_phrase.append([li[i],text.count(li[i])])
            counte_phrase_times.append(text.count(li[i]))
            counte_phrase_phrase.append(li[i])
#    counte_phrase.append([li[i],text.count(li[i])])
#    pdf=pd.DataFrame().append(counte_phrase)
#print(pdf.sort_values(1))
#print(sorted(counte_phrase,key=lambda counte_phrase:counte_phrase[1],reverse=True))
    pdf_=pd.DataFrame({"phrase":counte_phrase_phrase,
                       "times":counte_phrase_times}).sort_values("times",ascending=False)
    pdf_.to_csv('phrase_reg.csv',header=True,index=False)
    zhfont=FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf',size=14)
    sns.set(font=zhfont.get_name())
    sns.barplot("phrase", "times", palette="RdBu_r", data=pdf_.head(10))
    sns.barplot("phrase", "times", palette="RdBu_r", data=pdf_.head(-10))
Ejemplo n.º 16
0
from matplotlib.font_manager import FontProperties
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
pdf_=pd.read_csv("phrase_reg.csv",header=None)


zhfont = FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf', size=14)
plt.figure(figsize=[14,20])
sns.set(font=zhfont.get_name())
print(pdf_)
sns.barplot(0, 1, palette="RdBu_r", data=pdf_.head(20))
#sns.barplot(0, 1, palette="RdBu_r", data=pdf_.head(-10))

plt.show()
Ejemplo n.º 17
0
# -*- coding: utf-8 -*-

from os.path import exists
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Agg')

# apply japanese font
from matplotlib.font_manager import FontProperties
font_path = "/usr/share/fonts/truetype/migmix/migmix-1p-regular.ttf"
font_prop = FontProperties(fname=font_path)
matplotlib.rcParams["font.family"] = font_prop.get_name()

lstyles = [':', '--', '-']
colors = 'rgb'
# colors = 'kkk'


def main():
    fig, axs = plt.subplots(nrows=1, ncols=5, figsize=(16, 4))
    ax_ind = 0

    gmodel = 'BarabasiAlbert'
    n = 200
    for m in [2, 3, 4, 5, 6]:
        path_head = f'{gmodel}_m{m}_n{n}'
        legend = plot(path_head, axs[ax_ind], 50)
        ax_ind += 1
Ejemplo n.º 18
0
import pandas as pd
import numpy as np 
import seaborn as sns
from matplotlib import pyplot as plt
from matplotlib.font_manager import FontProperties

data = pd.read_excel('./datasets/主动暂停有欠费用户明细20181129.xlsx')



myfont=FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf',size=14)
sns.set(font=myfont.get_name(),style='whitegrid')


sns.countplot(data=data,x='分公司',hue='主副卡')

plt.show()
Ejemplo n.º 19
0
# Matplotlib试着让简单的事情更加简单,困难的事情变得可能,而Seaborn就是让困难的东西更加简单。
# 用Matplotlib最大的困难是其默认的各种参数,而Seaborn则完全避免了这一问题。

# sns 画热力图
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import mpld3
import numpy as np
import pandas as pd
font = FontProperties(fname=r"D:\materials\code\python\STZHONGS.TTF", size=14)
plt.switch_backend('agg')
fig, ax = plt.subplots()
index_return = index_return[index_return.columns].astype(float)
sns.set(font=font.get_name())
sns.heatmap(index_return, annot=True, fmt='.2%', center=0.1)
plt.ylabel('Step', fontsize=18)
Ejemplo n.º 20
0
# -*- coding: utf-8 -*-

import pandas as pd
from datetime import timedelta, datetime
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import numpy as np
import os

fontpath = 'C:\Windows\Fonts\msgothic.ttc'
fontproperty = FontProperties(fname=fontpath)
plt.rcParams['font.family'] = fontproperty.get_name()


class DateChart(object):
    def __init__(self, firstdate, lastdate):
        self.fig = plt.figure(figsize=(15, 15))
        self.ax = self.fig.subplots()
        self.set_firstdate(firstdate)
        self.set_lastdate(lastdate)

    def set_firstdate(self, d):
        self.firstdate = d

    def set_lastdate(self, d):
        self.lastdate = d

    def set_datelabels(self):
        xmajor_ticks = []
        xminor_ticks = []
        xmajor_labels = []
Ejemplo n.º 21
0
import tensorflow as tf
import numpy as np
import random
import math
import os
import xlwt
import matplotlib.pyplot as plt
from os import path
from matplotlib.font_manager import FontProperties
import sys

font_path = '/usr/share/fonts/truetype/takao-gothic/TakaoPGothic.ttf'
font_prop = FontProperties(fname=font_path)
plt.rcParams['font.family'] = font_prop.get_name()

# import load_notMNIST_1031

# np.random.seed(20160612)
# tf.set_random_seed(20160612)
np.random.seed(20171109)
tf.set_random_seed(20171109)

image_size = 28 * 28 * 1
output_size = 10
batchsize = 10
hidden_unit_number = 500
input_channel = 1
input_width = int(np.sqrt(image_size))

dataset_flag = 0
bias_ReLU = 0.1  #0.01
Ejemplo n.º 22
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
39. Zipfの法則
単語の出現頻度順位を横軸,その出現頻度を縦軸として,両対数グラフをプロットせよ.
"""

import n36
import matplotlib.pyplot as plt

from matplotlib.font_manager import FontProperties
plt.style.use('ggplot')
plt.rcParams['figure.figsize'] = 14, 10

fp = FontProperties(fname="/Library/Fonts/Osaka.ttf")
plt.rcParams['font.family'] = fp.get_name()


def main():
    counter = n36.main()
    plt.figure()
    plt.xscale('log')
    plt.yscale('log')
    plt.plot(sorted(list(counter.values()), reverse=True), range(1, len(list(counter)) + 1))
    plt.savefig('fig39.png')

if __name__ == '__main__':
    main()
Ejemplo n.º 23
0
import os
import jieba
import pickle
import seaborn
import numpy as np
import pandas as pd
from scipy.misc import imread
from pyecharts import Map
from wordcloud import WordCloud
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

font = FontProperties(fname=r"simkai.ttf", size=12)
seaborn.set(font=font.get_name())
'''画柱状图'''


def drawBar(data, x_label, y_label, title, savepath='results'):
    if not os.path.exists(savepath):
        os.mkdir(savepath)
    ax = seaborn.barplot(x=x_label, y=y_label, palette="RdBu_r", data=data)
    ax.set_title(title)
    plt.show()
    fig = ax.get_figure()
    fig.savefig(os.path.join(savepath, title + '.png'))


f = open('data.pkl', 'rb')
data = pickle.load(f)
prices = []
for key, value in data.items():
Ejemplo n.º 24
0
class Chart:
  def __init__(self, props, subdefaults):
    self.file = None
    self.filename = None
    self.props = {
      "imageType":	  "png",	# Output image type.
      "dpi":		  72,		# Image DPI resolution.
      "width":		  800,		# Output image width in pixels (vs. DPI).
      "height":		  600,		# Output image height in pixels (vs. DPI).
      "padding":	  50,		# Padding around the figure edge, in pixels.
      "textPadding":	  3,		# Padding around text, in pixels.
      "fontFamily":	  "sans-serif",	# Font family.
      "fontName":	  "Luxi Sans",	# Font name.
      "fontSize":	  12,		# Size of non-title text, in pixels.
      "titleFontName":	  "Bitstream Vera Sans",
      "titleFontSize":	  18,		# Size of title text, in pixels.
      "subtitleFontSize": 14,		# Size of subtitle text, in pixels.
      "axtitleFontSize":  16,		# Size of axis title text, in pixels.
      "xAxisScale":	  "lin",	# X axis scale, lin or log.
      "yAxisScale":	  "lin",	# Y axis scale, lin or log.
      "square":		  False,		# Force square layout.
      "integral":   False, #force integral display on legend
      "notitle": False, #suppress title
      "nolabels": False, #suppress axis labels
      "sort":False, #sort items and legend entries by value
      "max_legend":100 #maximum items in the legend
    }
    for (k, v) in subdefaults.iteritems():
      self.props[k] = v
    for (k, v) in props.iteritems():
      self.props[k] = v

    self.font = FontProperties()
    self.font.set_family(self.get('fontFamily'))
    self.font.set_name(self.get('fontName'))
    self.font.set_size(float(self.get('fontSize')))
    self.tfont = FontProperties()
    self.tfont.set_family(self.get('titleFontFamily', self.font.get_family()[-1]))
    self.tfont.set_name(self.get('titleFontName', self.font.get_name()))
    self.tfont.set_size(self.get('titleFontSize', self.font.get_size()))
    self.tfont.set_weight('bold')
    self.sfont = FontProperties()
    self.sfont.set_family(self.get('subtitleFontFamily', self.tfont.get_family()[-1]))
    self.sfont.set_name(self.get('subtitleFontName', self.tfont.get_name()))
    self.sfont.set_size(self.get('subtitleFontSize', self.tfont.get_size()))
    self.afont = FontProperties()
    self.afont.set_family(self.get('axtitleFontFamily', self.tfont.get_family()[-1]))
    self.afont.set_name(self.get('axtitleFontName', self.tfont.get_name()))
    self.afont.set_size(self.get('axtitleFontSize', self.tfont.get_size()))
    self.afont.set_weight('bold')

  def __del__(self):
    if self.file != None:
      os.close(self.file)

  def get(self, key, default=None):
    return getattr(self, key, self.props.get(key, default))

  def draw(self):
    (fig, canvas, w, h) = self.canvas()
    fig.text(.5, .5, "No data.", horizontalalignment='center', fontproperties=self.font)
    return self.save(fig, canvas)

  def legend(self):
    (fig, canvas, w, h) = self.canvas()
    fig.text(.5, .5, "No legend.", horizontalalignment='center', fontproperties=self.font)
    return self.save(fig, canvas)

  def details(self):
    return {}

  def canvas(self):
    type = self.get("imageType", "png")
    fig = Figure()
    if type == "png":
      canvas = FigureCanvasAgg(fig)
      (self.file, self.filename) = mkstemp(".%s" % type)
    elif type == "svg":
      canvas = FigureCanvasSVG(fig)
      (self.file, self.filename) = mkstemp(".%s" % type)
    elif type == "pdf":
      canvas = FigureCanvasPdf(fig)
      (self.file, self.filename) = mkstemp(".%s" % type)
    elif type == "ps" or type == "eps":
      canvas = FigureCanvasPS(fig)
      (self.file, self.filename) = mkstemp(".%s" % type)
    else:
      raise "Invalid render target requested"

    # Set basic figure parameters
    dpi = float(self.get('dpi'))
    (w, h) = (float(self.get('width')), float(self.get('height')))
    (win, hin) = (w/dpi, h/dpi)
    fig.set_size_inches(win, hin)
    fig.set_dpi(dpi)
    fig.set_facecolor('white')
    return (fig, canvas, w, h)

  def save(self, fig, canvas):
    canvas.draw()
    if not self.filename:
      canvas.print_figure(self.file, dpi=float(self.get('dpi')))
      return self.file
    else:
      canvas.print_figure(self.filename, dpi=float(self.get('dpi')))
      f = file(self.filename, "r") # PS backend writes over the file
      os.remove(self.filename)     #    return os.fdopen(self.file)
      os.close(self.file)
      self.file = None
      self.filename = None
      return f

  def prepare(self):
    # Create canvas and determine figure parameters
    (fig, canvas, w, h) = self.canvas()
    dpif = float(self.get('dpi')) / 72
    padding = float(self.get('padding')) * dpif / h
    textPadding = float(self.get('textPadding')) * dpif
    titleFontSize = float(self.get('titleFontSize'))
    axFontSize = float(self.get('axtitleFontSize'))
    subFontSize = float(self.get('subtitleFontSize'))
    title = self.get("title", "").split("\n")
    if not self.get("notitle",False):
      hsub = (len(title)-1) * (subFontSize * dpif + 4) + textPadding
      htitle = hsub + titleFontSize * dpif + textPadding * 2
    else:
      hsub = 0
      htitle = 0
    if self.get("nolabels",False):
      padding = 0

    # Configure axes
    if self.get('square'):
      minsize = 1 - 2*padding
      axrect = (.5 - minsize/2 * h/w, padding, h/w * minsize, minsize)
    else:
      axrect = (padding, padding, 1 - 1.25*padding, 1 - htitle/h - padding)
    ax = fig.add_axes(axrect)
    #frame = ax.get_frame()
    #frame.set_fill(False)

    xlog = (str(self.get('xAxisScale', "lin")) == 'log')
    ylog = (str(self.get('yAxisScale', "lin")) == 'log')
    if xlog:
      ax.semilogx()
    if ylog:
      ax.semilogy()

    setp(ax.get_xticklabels(), fontproperties=self.font)
    setp(ax.get_yticklabels(), fontproperties=self.font)
    setp(ax.get_xticklines(), markeredgewidth=2.0, zorder=4.0)
    setp(ax.get_yticklines(), markeredgewidth=2.0)
    ax.grid(True, alpha=0.25, color='#000000', linewidth=0.1)

    # Set titles
    if not self.get("notitle",False):
      ax.title = ax.text(.5, 1+(hsub+textPadding)/(axrect[-1]*h), title[0],
                      verticalalignment='bottom',
                      horizontalalignment='center',
                      transform=ax.transAxes,
                      clip_box=None,
                      fontproperties=self.tfont)
      ax._set_artist_props(ax.title)
      if len(title) > 1:
        ax.subtitle = ax.text(.5, 1+textPadding/(axrect[-1]*h), "\n".join(title[1:]),
                           verticalalignment='bottom',
                           horizontalalignment='center',
                           transform=ax.transAxes,
                           clip_box=None,
                           fontproperties=self.sfont)

    if not self.get("nolabels",False):
      ax.set_xlabel(self.get("xAxisTitle", ""), fontproperties=self.afont)
      ax.set_ylabel(self.get("yAxisTitle", ""), fontproperties=self.afont)
    return (fig, canvas, ax)

  def map(self):
    return ''

  def make(self):
    img = self.draw().read()
    legend = self.legend().read()
    map = self.map()
    return img,legend,map
Ejemplo n.º 25
0
    def plotResultBarChart(self):

        tp = []
        fp = []
        tn = []
        fn = []
        precisions = []
        recalls = []
        f1 = []
        category = []

        for key, cluster in self.data.clusters.items():
            if len(cluster.test) > 0:
                category.append(cluster.name)
                results = self.nn.specificResult(self.data, cluster.name)
                tp.append(results["truePositivesPercent"])
                tn.append(results["trueNegativesPercent"])
                fp.append(results["falsePositivesPercent"])
                fn.append(results["falseNegativesPercent"])
                precisions.append(results["precision"])
                recalls.append(results["recall"])
                f1.append(results["f1"])
        category.append("平均")
        self.addMean(tp)
        self.addMean(tn)
        self.addMean(fp)
        self.addMean(fn)
        self.addMean(precisions)
        self.addMean(recalls)
        self.addMean(f1)

        n_groups = len(f1)

        fig, ax = plt.subplots()

        font = FontProperties(fname='./Osaka.ttc', size=10)
        rcParams['font.family'] = font.get_name()

        bar_width = 0.05
        opacity = 0.8

        index = np.arange(n_groups)

        w = 0
        ax.bar(index + w,
               tp,
               bar_width,
               alpha=opacity,
               color='lime',
               label='true positives')
        w += bar_width
        ax.bar(index + w,
               tn,
               bar_width,
               alpha=opacity,
               color='green',
               label='true negatives')
        w += bar_width
        ax.bar(index + w,
               fp,
               bar_width,
               alpha=opacity,
               color='red',
               label='false positives')
        w += bar_width
        ax.bar(index + w,
               fn,
               bar_width,
               alpha=opacity,
               color='orangered',
               label='false negatives')
        w += bar_width * 2
        ax.bar(index + w,
               precisions,
               bar_width,
               alpha=opacity,
               color='blue',
               label='precision')
        w += bar_width
        ax.bar(index + w,
               recalls,
               bar_width,
               alpha=opacity,
               color='mediumslateblue',
               label='recall')
        w += bar_width
        ax.bar(index + w,
               f1,
               bar_width,
               alpha=opacity,
               color='cyan',
               label='f1 score')

        ax.set_xlabel('Group')
        ax.set_ylabel('Score')
        ax.set_title('log clustering results on testing dataset')
        ax.set_xticks(index + bar_width * 4)
        ax.set_xticklabels(category)
        ax.legend()

        fig.tight_layout()
        plt.show()
Ejemplo n.º 26
0
def tojson():
    df = pd.read_csv('kddidata.csv', header=None, skiprows=1)
    data = []
    time = []
    time_i = []
    humidity = []
    temperature = []
    brightness = []
    ultraviolet = []
    atmopressure = []
    volume = []
    discomfort = []
    heatstrokerisk = []
    co2 = []

    for i in range(len(df)):
        data.append('value')
        time.append(df.iloc[i, 3])
        humidity.append(df.iloc[i, 4])
        temperature.append(df.iloc[i, 5])
        brightness.append(df.iloc[i, 6])
        ultraviolet.append(df.iloc[i, 7])
        atmopressure.append(df.iloc[i, 8])
        volume.append(df.iloc[i, 9])
        discomfort.append(df.iloc[i, 10])
        heatstrokerisk.append(df.iloc[i, 11])
        co2.append(df.iloc[i, 12])

    global nowtime, nowhumidity, nowtemperature, nowbrightness, nowultraviolet, nowatmopressure, nowvolume, nowdiscomfort, nowheatstrokerisk, nowco

    for i in (reversed(co2)):
        if i == i:
            nowco2 = i
            break

    for i in range(len(df))[::-1]:
        if temperature[i] == temperature[i]:
            nownum = i
            break

    nowtime = time[nownum]
    nowhumidity = humidity[nownum]
    nowtemperature = temperature[nownum]
    nowbrightness = brightness[nownum]
    nowultraviolet = ultraviolet[nownum]
    nowatmopressure = atmopressure[nownum]
    nowvolume = volume[nownum]
    nowdiscomfort = discomfort[nownum]
    nowheatstrokerisk = heatstrokerisk[nownum]
    nowco = nowco2

    font_path = '/usr/share/fonts/truetype/takao-gothic/TakaoPGothic.ttf'
    font_prop = FontProperties(fname=font_path)
    pyplot.rcParams['font.family'] = font_prop.get_name()
    pyplot.subplot(121)
    pyplot.title('CO2 concentration')
    p1 = pyplot.bar(1, nowco, width=0.8, color='green')
    pyplot.plot([0, 2], [2000, 2000], "red", linestyle='dashed')
    pyplot.annotate('現在co2濃度',
                    xy=(1, nowco + 10),
                    xytext=(1.2, nowco + 300),
                    arrowprops=dict(shrink=0.1))
    pyplot.annotate('co2濃度警戒線',
                    xy=(1, 2000 - 10),
                    xytext=(1.2, 2000 - 300),
                    arrowprops=dict(shrink=0.1))
    pyplot.subplot(122)
    pyplot.title('Discomfort index')
    pyplot.ylim(50, 80)
    p2 = pyplot.bar(1, nowdiscomfort, width=0.8, color='blue')
    pyplot.plot([0, 2], [75, 75], "red", linestyle='dashed')
    pyplot.plot([0, 2], [60, 60], "red", linestyle='dashed')
    pyplot.annotate('不快指数警戒線',
                    xy=(1, 75 + 1),
                    xytext=(1.2, 75 + 3),
                    arrowprops=dict(shrink=0.1))
    pyplot.annotate('不快指数警戒線',
                    xy=(1, 60 - 1),
                    xytext=(1.2, 60 - 3),
                    arrowprops=dict(shrink=0.1))
    #pyplot.savefig('kddifigure.png')
    # #date draw
    # for i in time:
    #     time_i.append(dt.strptime(i,'%Y/%m/%d %H:%M:%S'))

    # time_j=[]
    # for i in time_i:
    #     time_j.append('{}:{}'.format(i.hour,i.minute))

    # def make_patch_spines_invisible(ax):
    #     ax.set_frame_on(True)
    #     ax.patch.set_visible(False)
    #     for sp in ax.spines.values():
    #         sp.set_visible(False)

    # fig,host=pyplot.subplots(figsize=(20,10))
    # fig.subplots_adjust(right=0.5)
    # par1=host.twinx()
    # par2=host.twinx()
    # par3=host.twinx()
    # par4=host.twinx()
    # par5=host.twinx()
    # par6=host.twinx()
    # par7=host.twinx()
    # par8=host.twinx()

    # # Offset the right spine of par2.  The ticks and label have already been
    # # placed on the right by twinx above.
    # par2.spines["right"].set_position(("axes", 1.1))
    # make_patch_spines_invisible(par2)
    # par2.spines["right"].set_visible(True)
    # #
    # par3.spines["right"].set_position(("axes", 1.2))
    # make_patch_spines_invisible(par3)
    # par3.spines["right"].set_visible(True)
    # #
    # par4.spines["right"].set_position(("axes", 1.3))
    # make_patch_spines_invisible(par4)
    # par4.spines["right"].set_visible(True)
    # #
    # par5.spines["right"].set_position(("axes", 1.5))
    # make_patch_spines_invisible(par5)
    # par5.spines["right"].set_visible(True)
    # #
    # par6.spines["right"].set_position(("axes", 1.7))
    # make_patch_spines_invisible(par6)
    # par6.spines["right"].set_visible(True)
    # #
    # par7.spines["right"].set_position(("axes", 1.9))
    # make_patch_spines_invisible(par7)
    # par7.spines["right"].set_visible(True)
    # #
    # par8.spines["right"].set_position(("axes",2))
    # make_patch_spines_invisible(par8)
    # par8.spines["right"].set_visible(True)
    # #
    # p1, = host.plot(time_j,volume,'darkgreen',  label="volume")
    # p2, = par1.plot(time_j,temperature,'pink', label="Temperature",antialiased="True")
    # p3, = par2.plot(time_j,humidity, 'b',label="humidity",antialiased="True")
    # p4, = par3.plot(time_j,brightness, 'y',label="brightness",antialiased="True")
    # p5, = par4.plot(time_j,ultraviolet, 'violet',label="ultraviolet",antialiased="True")
    # p6, = par5.plot(time_j,atmopressure, 'grey',label="atmopressure",antialiased="True")
    # p7, = par6.plot(time_j,discomfort, 'peru',label="discomfort",antialiased="True")
    # p8, = par7.plot(time_j,heatstrokerisk, 'r',label="heatstrokerisk",antialiased="True")
    # p9, = par8.plot(time_j,co2, 'lightgreen',label="co2",antialiased="True")

    # host.set_xlabel("time")
    # host.set_ylabel("volume")
    # par1.set_ylabel("Temperature")
    # par2.set_ylabel("humidity")
    # par3.set_ylabel("brightness")
    # par4.set_ylabel("ultraviolet")
    # par5.set_ylabel("atmopressure")
    # par6.set_ylabel("discomfort")
    # par7.set_ylabel("heatstrokerisk")
    # par8.set_ylabel("co2")

    # tkw = dict(size=4, width=1.5)
    # host.tick_params(axis='y', colors=p1.get_color(), **tkw)
    # par1.tick_params(axis='y', colors=p2.get_color(), **tkw)
    # par2.tick_params(axis='y', colors=p3.get_color(), **tkw)
    # par3.tick_params(axis='y', colors=p4.get_color(), **tkw)
    # par4.tick_params(axis='y', colors=p5.get_color(), **tkw)
    # par5.tick_params(axis='y', colors=p6.get_color(), **tkw)
    # par6.tick_params(axis='y', colors=p7.get_color(), **tkw)
    # par7.tick_params(axis='y', colors=p8.get_color(), **tkw)
    # par8.tick_params(axis='y', colors=p9.get_color(), **tkw)
    # host.tick_params(axis='x',labelsize=8,**tkw)

    pyplot.savefig('kddifigure.png')

    return nowtime, nowhumidity, nowtemperature, nowbrightness, nowultraviolet, nowatmopressure, nowvolume, nowdiscomfort, nowheatstrokerisk, nowco
Ejemplo n.º 27
0
import datetime

import pandas as pd
import numpy as np

from matplotlib import pyplot as plt
import seaborn as sns

from matplotlib.font_manager import FontProperties
#dir_fonts=FontProperties(fname='/System/Library/Fonts/Menlo.ttc', size=12, style='oblique', variant='normal');
font_hiraginoProNW4 = '/System/Library/Fonts/ヒラギノ丸ゴ ProN W4.ttc'
dir_fonts = FontProperties(fname=font_hiraginoProNW4,
                           size=12,
                           style='oblique',
                           variant='normal')
plt.rcParams['font.family'] = dir_fonts.get_name()

from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

import matplotlib as mpl
#import matplotlib.style
mpl.style.use('seaborn-dark-palette')
# classic, seaborn-pastel
#mpl.style.use('tableau-colorblind10')

CB91_Blue = '#2CBDFE'
CB91_Green = '#47DBCD'
CB91_Pink = '#F3A0F2'
CB91_Purple = '#9D2EC5'
CB91_Violet = '#661D98'
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

font_path = '/usr/share/fonts/truetype/takao-gothic/TakaoPGothic.ttf'
font_prop = FontProperties(fname=font_path)
matplotlib.rcParams['font.family'] = font_prop.get_name()

# モデルをインポート
from LinearRegression import LinearRegression


X = np.random.randn(100,1)
t = np.random.randint(-100,100 ,size=(100,1)) * X


model = LinearRegression()
cost = []

for i in range(1000):
    #仮説の計算
    y = model.predict(X)

    #目的関数(コスト関数)の値を記録
    J = model.cost_function(y,t)
    cost.append(J)
    
    #パラメータの更新(学習) 
    model.gradient_descent(X,y,t)
Ejemplo n.º 29
0
import calendar
import csv
import glob
from collections import defaultdict

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from matplotlib.font_manager import FontProperties

myfont = FontProperties(fname="SourceHanSansCN-Light.otf")

sns.set(
    style="ticks",
    font=myfont.get_name(),
    rc={
        "figure.figsize": [16, 9],
        "text.color": "white",
        "axes.labelcolor": "white",
        "axes.edgecolor": "white",
        "xtick.color": "white",
        "ytick.color": "white",
        "axes.facecolor": "#443941",
        "figure.facecolor": "#443941",
    },
)

# 不全,需要手动添加
HALLS = {
    "东一",
Ejemplo n.º 30
0
from .report import genwordcloud
from .utils.metrics import entropyc

from .utils import iqr

#from sklearn.neighbors import KernelDensity
import matplotlib.pyplot as plt
import seaborn as sns

_thisdir = os.path.split(__file__)[0]
# default chinese font
from matplotlib.font_manager import FontProperties
font_path=config.font_path
if font_path:
    myfont=FontProperties(fname=font_path)
    sns.set(font=myfont.get_name())


__all__=['type_of_var',
         'describe',
         'plot',
         'features_analysis',
         'distributions',
         'AnalysisReport',
         'ClassifierReport']


def _freedman_diaconis_bins(a):
    """Calculate number of hist bins using Freedman-Diaconis rule."""
    # From http://stats.stackexchange.com/questions/798/
    a = np.asarray(a)
Ejemplo n.º 31
0
from .report import genwordcloud
from .utils.metrics import entropyc

from .utils import iqr

#from sklearn.neighbors import KernelDensity
import matplotlib.pyplot as plt
import seaborn as sns

_thisdir = os.path.split(__file__)[0]
# default chinese font
from matplotlib.font_manager import FontProperties
font_path = config.font_path
if font_path:
    myfont = FontProperties(fname=font_path)
    sns.set(font=myfont.get_name())

__all__ = [
    'type_of_var', 'describe', 'plot', 'features_analysis', 'distributions',
    'AnalysisReport', 'ClassifierReport'
]


def _freedman_diaconis_bins(a):
    """Calculate number of hist bins using Freedman-Diaconis rule."""
    # From http://stats.stackexchange.com/questions/798/
    a = np.asarray(a)
    assert len(a.shape) > 0
    assert len(a) > 0
    h = 2 * iqr(a) / (len(a)**(1 / 3))
    # fall back to sqrt(a) bins if iqr is 0
Ejemplo n.º 32
0
from traitsui.api import Item, View
from traitsui.menu import OKButton, CancelButton

__QS_MainPath__ = os.path.split(os.path.realpath(__file__))[0]
__QS_LibPath__ = __QS_MainPath__+os.sep+"Lib"
__QS_ConfigPath__ = os.path.expanduser("~")+os.sep+"QuantStudioConfig"

from matplotlib.pylab import mpl
if platform.system()=="Windows":
    mpl.rcParams['font.sans-serif'] = ["SimHei"]
elif platform.system()=="Darwin":
    if os.path.isfile("/Library/Fonts/Arial Unicode.ttf"):
        from matplotlib.font_manager import FontProperties
        Font = FontProperties(fname="/Library/Fonts/Arial Unicode.ttf")
        mpl.rcParams["font.family"] = Font.get_family()
        mpl.rcParams["font.sans-serif"] = Font.get_name()
mpl.rcParams['axes.unicode_minus'] = False

# Quant Studio 系统错误
class __QS_Error__(Exception):
    """Quant Studio 错误"""
    pass

# Quant Studio 系统对象
class __QS_Object__(HasTraits):
    """Quant Studio 系统对象"""
    def __init__(self, sys_args={}, config_file=None, **kwargs):
        self._QS_Logger = kwargs.pop("logger", None)
        if self._QS_Logger is None: self._QS_Logger = logging.getLogger()
        super().__init__(**kwargs)
        self._LabelTrait = {}
Ejemplo n.º 33
0
Archivo: plot.py Proyecto: sshi27/plot
import json, ast, sys

import matplotlib
from matplotlib.font_manager import FontProperties

import matplotlib.pyplot as plt

fontProp = FontProperties(fname="./LinLibertine_R.ttf")

# plt.rc('text', usetex=True)
matplotlib.rcParams.update({
  'text.latex.preamble': "\\usepackage{libertine}\n\\usepackage[libertine]{newtxmath}\n\\usepackage{sfmath}\n\\usepackage[T1]{fontenc}",
  'pdf.fonttype': 42,
  'ps.fonttype': 42,
  'font.family': fontProp.get_name(),  # fontProp.get_name(),
  'text.usetex': True,
  # 'font.serif': ['Times New Roman Bold', 'FreeSerifBold'],
})
matplotlib.font_manager._rebuild()

from multiple_line import MultipleLines
from parallel_bar import ParallelBars
from annotated_bar import AnnotatedBars
from violin import Violin
from cdf import Cdf
from heatmap import HeatMap
import rapidjson
import copy

forth = [114, 83]
third = [173, 122]
Ejemplo n.º 34
0
	Charles的皮卡丘
'''
import os
import jieba
import pickle
import seaborn
import numpy as np
import pandas as pd
from scipy.misc import imread
from pyecharts import Map
from wordcloud import WordCloud
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

font = FontProperties(fname=r"simkai.ttf", size=12)
seaborn.set(font=font.get_name())
'''画柱状图'''


def drawBar(data, x_label, y_label, title, savepath='results'):
    if not os.path.exists(savepath):
        os.mkdir(savepath)
    ax = seaborn.barplot(x=x_label, y=y_label, palette="RdBu_r", data=data)
    ax.set_title(title)
    plt.show()
    fig = ax.get_figure()
    fig.savefig(os.path.join(savepath, title + '.png'))


'''画地图'''