ax.set_ylim([0, 100]) ax.set_xlim([0, POINTS]) ax.set_autoscale_on(False) ax.set_xticks([]) ax.set_yticks(range(0, 101, 10)) ax.grid(True) # 执行用户进程的时间百分比 user = [None] * POINTS # 执行内核进程和中断的时间百分比 sys = [None] * POINTS # CPU处于空闲状态的时间百分比 idle = [None] * POINTS l_user, = ax.plot(range(POINTS), user, label='User %') l_sys, = ax.plot(range(POINTS), sys, label='Sys %') l_idle, = ax.plot(range(POINTS), idle, label='Idle %') ax.legend(loc='upper center', ncol=4, prop=font_manager.FontProperties(size=10)) bg = fig.canvas.copy_from_bbox(ax.bbox) def cpu_usage(): t = p.cpu_times() return [t.user, t.system, t.idle] before = cpu_usage() def get_cpu_usage(): global before now = cpu_usage() delta = [now[i] - before[i] for i in range(len(now))]
import matplotlib.pyplot as plt import numpy as np from matplotlib import font_manager, rc from matplotlib import style font_name = font_manager.FontProperties( fname="c:/Windows/Fonts/malgun.ttf").get_name() rc('font', family=font_name) style.use('ggplot') industry = [ '통신업', '의료정밀', '운수창고업', '의약품', '음식료품', '전기가스업', '서비스업', '전기전자', '종이목재', '증권' ] fluctuations = [1.83, 1.30, 1.30, 1.26, 1.06, 0.93, 0.77, 0.68, 0.65, 0.61] fig = plt.figure(figsize=(12, 8)) ax = fig.add_subplot(111) ypos = np.arange(10) rects = plt.barh(ypos, fluctuations, align='center', height=0.5) plt.yticks(ypos, industry) for i, rect in enumerate(rects): ax.text(0.95 * rect.get_width(), rect.get_y() + rect.get_height() / 2.0, str(fluctuations[i]) + '%', ha='right', va='center') plt.rcParams['axes.unicode_minus'] = False
def set_units(self, unit): self.axes['Sensor PV'].set_ylabel({'Temperature': 'Temperature (°C)', 'Voltage': 'Voltage (mV)'}[unit], fontproperties=fm.FontProperties(fname='Fonts/Roboto-Regular.ttf', size=14)) self.figure.canvas.draw() self.figure.tight_layout()
def add_scale_bar( ax, metric_distance=4, unit="km", at_x=(0.05, 0.5), at_y=(0.08, 0.11), max_stripes=5, ytick_label_margins=0.25, fontsize=8, font_weight="bold", rotation=0, zorder=999, paddings={"xmin": 0.05, "xmax": 0.05, "ymin": 1.5, "ymax": 0.5}, bbox_kwargs={"facecolor": "white", "edgecolor": "black", "alpha": 0.5}, ): """ Add a scale bar to the map. Args: ax (cartopy.mpl.geoaxes.GeoAxesSubplot | cartopy.mpl.geoaxes.GeoAxes): required cartopy GeoAxesSubplot object. metric_distance (int | float, optional): length in meters of each region of the scale bar. Default to 4. unit (str, optinal): scale bar distance unit. Default to "km" at_x (float, optional): target axes X coordinates (0..1) of box (= left, right). Default to (0.05, 0.2). at_y (float, optional): axes Y coordinates (0..1) of box (= lower, upper). Deafult to (0.08, 0.11). max_stripes (int, optional): typical/maximum number of black+white regions. Default to 5. ytick_label_margins (float, optional): Location of distance labels on the Y axis. Default to 0.25. fontsize (int, optional): scale bar text size. Default to 8. font_weight (str, optional):font weight. Default to 'bold'. rotation (int, optional): rotation of the length labels for each region of the scale bar. Default to 0. zorder (float, optional): z order of the text bounding box. paddings (dict, optional): boundaries of the box that contains the scale bar. bbox_kwargs (dict, optional): style of the box containing the scale bar. """ warnings.filterwarnings("ignore") # -------------------------------------------------------------------------- # Auxiliary functions def _crs_coord_project(crs_target, xcoords, ycoords, crs_source): """ metric coordinates (x, y) from cartopy.crs_source""" axes_coords = crs_target.transform_points(crs_source, xcoords, ycoords) return axes_coords def _add_bbox(ax, list_of_patches, paddings={}, bbox_kwargs={}): """ Description: This helper function adds a box behind the scalebar: Code inspired by: https://stackoverflow.com/questions/17086847/box-around-text-in-matplotlib """ zorder = list_of_patches[0].get_zorder() - 1 xmin = min([t.get_window_extent().xmin for t in list_of_patches]) xmax = max([t.get_window_extent().xmax for t in list_of_patches]) ymin = min([t.get_window_extent().ymin for t in list_of_patches]) ymax = max([t.get_window_extent().ymax for t in list_of_patches]) xmin, ymin = ax.transData.inverted().transform((xmin, ymin)) xmax, ymax = ax.transData.inverted().transform((xmax, ymax)) xmin = xmin - ((xmax - xmin) * paddings["xmin"]) ymin = ymin - ((ymax - ymin) * paddings["ymin"]) xmax = xmax + ((xmax - xmin) * paddings["xmax"]) ymax = ymax + ((ymax - ymin) * paddings["ymax"]) width = xmax - xmin height = ymax - ymin # Setting xmin according to height rect = patches.Rectangle( (xmin, ymin), width, height, facecolor=bbox_kwargs["facecolor"], edgecolor=bbox_kwargs["edgecolor"], alpha=bbox_kwargs["alpha"], transform=ax.projection, fill=True, clip_on=False, zorder=zorder, ) ax.add_patch(rect) return ax # -------------------------------------------------------------------------- old_proj = ax.projection ax.projection = ccrs.PlateCarree() # Set a planar (metric) projection for the centroid of a given axes projection: # First get centroid lon and lat coordinates: lon_0, lon_1, lat_0, lat_1 = ax.get_extent(ax.projection.as_geodetic()) central_lon = np.mean([lon_0, lon_1]) central_lat = np.mean([lat_0, lat_1]) # Second: set the planar (metric) projection centered in the centroid of the axes; # Centroid coordinates must be in lon/lat. proj = ccrs.EquidistantConic( central_longitude=central_lon, central_latitude=central_lat ) # fetch axes coordinates in meters x0, _, y0, y1 = ax.get_extent(proj) ymean = np.mean([y0, y1]) # set target rectangle in-visible-area (aka 'Axes') coordinates axfrac_ini, _ = at_x ayfrac_ini, ayfrac_final = at_y # choose exact X points as sensible grid ticks with Axis 'ticker' helper converted_metric_distance = convert_SI(metric_distance, unit, "m") xcoords = [] ycoords = [] xlabels = [] for i in range(0, 1 + max_stripes): dx = (converted_metric_distance * i) + x0 xlabels.append(metric_distance * i) xcoords.append(dx) ycoords.append(ymean) # Convertin to arrays: xcoords = np.asanyarray(xcoords) ycoords = np.asanyarray(ycoords) # Ensuring that the coordinate projection is in degrees: x_targets, _, _ = _crs_coord_project(ax.projection, xcoords, ycoords, proj).T x_targets = [x + (axfrac_ini * (lon_1 - lon_0)) for x in x_targets] # Checking x_ticks in axes projection coordinates # print('x_targets', x_targets) # Setting transform for plotting transform = ax.projection # grab min+max for limits xl0, xl1 = x_targets[0], x_targets[-1] # calculate Axes Y coordinates of box top+bottom yl0, yl1 = [ lat_0 + ay_frac * (lat_1 - lat_0) for ay_frac in [ayfrac_ini, ayfrac_final] ] # calculate Axes Y distance of ticks + label margins y_margin = (yl1 - yl0) * ytick_label_margins # fill black/white 'stripes' and draw their boundaries fill_colors = ["black", "white"] i_color = 0 filled_boxs = [] for xi0, xi1 in zip(x_targets[:-1], x_targets[1:]): # fill region filled_box = plt.fill( (xi0, xi1, xi1, xi0, xi0), (yl0, yl0, yl1, yl1, yl0), fill_colors[i_color], transform=transform, clip_on=False, zorder=zorder, ) filled_boxs.append(filled_box[0]) # draw boundary plt.plot( (xi0, xi1, xi1, xi0, xi0), (yl0, yl0, yl1, yl1, yl0), "black", clip_on=False, transform=transform, zorder=zorder, ) i_color = 1 - i_color # adding boxes _add_bbox(ax, filled_boxs, bbox_kwargs=bbox_kwargs, paddings=paddings) # add short tick lines for x in x_targets: plt.plot( (x, x), (yl0, yl0 - y_margin), "black", transform=transform, zorder=zorder, clip_on=False, ) # add a scale legend unit font_props = mfonts.FontProperties(size=fontsize, weight=font_weight) plt.text( 0.5 * (xl0 + xl1), yl1 + y_margin, unit, color="black", verticalalignment="bottom", horizontalalignment="center", fontproperties=font_props, transform=transform, clip_on=False, zorder=zorder, ) # add numeric labels for x, xlabel in zip(x_targets, xlabels): # print("Label set in: ", x, yl0 - 2 * y_margin) plt.text( x, yl0 - 2 * y_margin, "{:g}".format((xlabel)), verticalalignment="top", horizontalalignment="center", fontproperties=font_props, transform=transform, rotation=rotation, clip_on=False, zorder=zorder + 1, # bbox=dict(facecolor='red', alpha=0.5) # this would add a box only around the xticks ) # Adjusting figure borders to ensure that the scalebar is within its limits ax.projection = old_proj ax.get_figure().canvas.draw()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Aug 9 13:39:55 2020 @author: arti """ import pandas as pd import matplotlib.pyplot as plt from matplotlib import font_manager, rc font_path = './malgun.ttf' font_prop = font_manager.FontProperties(fname=font_path) df = pd.read_excel('Number_of_people_moving_IO_of_cities_and_provinces.xlsx') \ .fillna(method='ffill') mask = (df['전출지별'] == '서울특별시') & (df['전입지별'] != '서울특별시') df_seoul = df[mask] df_seoul = df_seoul.drop(['전출지별'], axis=1) df_seoul.rename({'전입지별': '전입지'}, axis=1, inplace=True) df_seoul.set_index('전입지', inplace=True) col_years = list(map(str, range(1970, 2018))) df_3 = df_seoul.loc[['충청남도', '경상북도', '강원도'], col_years] plt.style.use('ggplot') fig = plt.figure(figsize=(20, 5))
import pandas as pd from pandas import DataFrame import pandas.io.sql as pdsql import matplotlib import matplotlib.pyplot as plt import matplotlib.ticker as ticker from matplotlib import dates import matplotlib.font_manager as font_manager import seaborn as sns import mysql.connector # 맑은고딕체 sns.set(style="whitegrid", font="Malgun Gothic", font_scale=1.5) fp = font_manager.FontProperties(fname="C:\\WINDOWS\\Fonts\\malgun.TTF", size=15) def comma_volume(x, pos=None): s = '{:0,d}K'.format(int(x / 1000)) return s def comma_price(x, pos=None): s = '{:0,d}'.format(int(x)) return s def comma_percent(x, pos=None): s = '{:+.2f}'.format(x) return s major_date_formatter = dates.DateFormatter('%Y-%m-%d') minor_date_formatter = dates.DateFormatter('%m')
import time import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import matplotlib.font_manager as fm import pandas as pd import os import copy #------------------------------------------------------------------------------ path = "C:\\Users\\craig\\OneDrive\\桌面\\科技部相關檔案" os.chdir(path) #讓matplotlib補上中文顯示 myfont = fm.FontProperties(fname='C:/Windows/Fonts/kaiu.ttc') fig = plt.figure() t0 = time.clock() Data = pd.read_excel('DATA4.xlsx', header=0) Data = pd.DataFrame(Data) pre_x_train = np.array(Data.iloc[:3000, 2:-1]) pre_x_test = np.array(Data.iloc[3000:, 2:-1]) y_train = np.array(Data.iloc[:3000, 0]).reshape(-1, 1) y_test = np.array(Data.iloc[3000:, 0]).reshape(-1, 1) train_height = Data.iloc[:3000, 1] test_height = Data.iloc[3000:, 1]
import pandas as pd import numpy as np import scipy.optimize as opt from sklearn import preprocessing import matplotlib.pyplot as plt from matplotlib import rc, font_manager ticks_font = font_manager.FontProperties(family='Times New Roman', style='normal', size=12, weight='normal', stretch='normal') ax = plt.gca() ## Loading Data ## df = pd.read_csv('D:\Python\edx\Machine Learning\Classification\ChurnData.csv') with open('Log_Reg.txt', 'a') as f: print(df.head(), file=f) ## Preprocessing and selection ## df = df[[ 'tenure', 'age', 'address', 'income', 'ed', 'employ', 'equip', 'callcard', 'wireless', 'churn' ]] df['churn'] = df['churn'].astype('int') with open('Log_Reg.txt', 'a') as f: print(df.head(), file=f) print(df.shape, file=f) for col in df.columns: with open('Log_Reg.txt', 'a') as f: print(col, file=f)
# -*- coding: utf-8 -*- #%% 导入模块 import numpy as np import sklearn.datasets as ds from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.linear_model.stochastic_gradient import SGDRegressor from sklearn.cross_validation import cross_val_score from sklearn.preprocessing import StandardScaler import matplotlib.pyplot as plt import matplotlib.font_manager as fm myfont = fm.FontProperties(fname=u'C:\Windows\Fonts\simsun.ttc', size=16) #%% 模拟数据生成 def data_helper(n_samples=1000): ''' 产生数据样本点集合 样本点的特征X维度为1维,输出y的维度也为1维 输出是在输入的基础上加入了高斯噪声N(0,10) 产生的样本点数目为1000个 ''' X, y, coef = ds.make_regression(n_samples=n_samples, n_features=1, n_informative=3, noise=10, coef=True, random_state=0) # 将上面产生的样本点中的前50个设为异常点(外点) # 即:让前50个点偏离原来的位置,模拟错误的测量带来的误差 n_outliers = 100
output, alpha=0.75, lw=3, label=label, zorder=10) max_vals.append(output.max()) min_vals.append(output.min()) # Plot ground-truth time series. ground_truth = X_te_[i] max_vals.append(ground_truth.max()) min_vals.append(ground_truth.min()) ax.plot(ground_truth, c="k", alpha=0.3, lw=3, label='Ground truth', zorder=5) # Plot vertical line. ax.plot([len_input, len_input], [np.min(min_vals), np.max(max_vals)], lw=3, ls="--", c="k") # Legend. prop = fm.FontProperties(size=18) ax.legend(loc="best", prop=prop) fig.set_tight_layout(True) plt.show()
Author: K Email: [email protected] Github: https://github.com/7thMar Description: DPC 算法的实现和测试 """ import sys import matplotlib import scipy.cluster.hierarchy as sch import math import matplotlib.pyplot as plt import numpy as np import pandas as pd import scipy from multiprocessing import Process, Queue, Pool import matplotlib.font_manager as f cnfont = f.FontProperties( fname='/usr/share/fonts/wenquanyi/wqy-zenhei/wqy-zenhei.ttc') matplotlib.rcParams['axes.unicode_minus'] = False # plt.title('中文示例', fontproperties=cnfont) class DPC(object): """ 1. 读取点 2. 计算距离 3. 计算截断距离 dc 4. 计算局部密度 rho 5. 计算 delta 6. 确定 聚类中心 7. 聚类 8. 绘图 """
from matplotlib import pyplot as plt #import matplotlib.pyplot as plt from matplotlib import font_manager, rc font_path = "C:\Windows\Fonts\malgun.ttf" font_name = font_manager.FontProperties(fname=font_path).get_name() font = font_manager.FontProperties(fname=font_path, size=20) rc('font', family=font_name) x = ["2000", "2005", "2010", "2015", "2019"] ko = [11030, 18520, 22290, 28720, 33720] jp = [36230, 40560, 43440, 38840, 41690] ch = [940, 1760, 4340, 7940, 10410] plt.plot(x, ko, 'b-', label="한국") plt.plot(x, jp, 'r-', label="일본") plt.plot(x, ch, 'g-', label="중국") plt.title("한국 1인당 국민소득", fontproperties=font) plt.ylabel("dollars") plt.xlabel("년도") plt.legend() plt.savefig("한국 1인당 국민소득.png", dpi=600) plt.show()
from matplotlib import pyplot as plt import random import matplotlib from matplotlib import font_manager #matplotlib.rc windows和linux ''' font = {'family': 'monospace', 'weight': 'bold', 'size': 'larger'} matplotlib.rc("font",**font) ''' #另外一种设置字体的方式 my_font = font_manager.FontProperties(fname="/System/Library/Fonts/PingFang.ttc") x = range(0,120) y = [random.randint(20,35) for i in range(120)] plt.figure(figsize=(20,8),dpi=80) plt.plot(x,y) #调整x轴的刻度 _x = list(x) _xtick_lables = ['10点{}分'.format(i) for i in range(60)] _xtick_lables += ['11点{}分'.format(i) for i in range(60)] #取步长 plt.xticks(_x[::3],_xtick_lables[::3],rotation=45,fontproperties=my_font)#rotation旋转角度
Force33.append((N33[j] - N33[j - 1]) / (Disp2[j] - Disp2[j - 1]) * (Disp1[i] - Disp2[j - 1]) + N33[j - 1]) Force41.append((N41[j] - N41[j - 1]) / (Disp2[j] - Disp2[j - 1]) * (Disp1[i] - Disp2[j - 1]) + N41[j - 1]) Force42.append((N42[j] - N42[j - 1]) / (Disp2[j] - Disp2[j - 1]) * (Disp1[i] - Disp2[j - 1]) + N42[j - 1]) Force43.append((N43[j] - N43[j - 1]) / (Disp2[j] - Disp2[j - 1]) * (Disp1[i] - Disp2[j - 1]) + N43[j - 1]) Force2t.append((Force2[j] - Force2[j - 1]) / (Disp2[j] - Disp2[j - 1]) * (Disp1[i] - Disp2[j - 1]) + Force2[j - 1]) print(len(Force11), len(Force2t)) fontpath = '/usr/share/fonts/truetype/msttcorefonts/Arial.ttf' fontprop = fm.FontProperties(family='Arial', fname=fontpath, size=16) mpl.rcParams.update({'font.size': 16, 'font.family': 'Arial'}) plt.figure(figsize=(11, 5)) ax1 = plt.subplot(1, 2, 1) Force2g = [] for i in range(0, length2): rel = Force2[i] * 1.65 Force2g.append(rel) N12g.append((N12[i] + N22[i])) N32g.append((N32[i] + N42[i])) p1, = plt.plot(Force2g, N12g, color='black', label='Upper Steel Rods',
# this is d13 excercise for 3rd-party library "matplotlib" and "numpy" # date : 2019.3.30 # author by : qiming import matplotlib.pyplot as plt import matplotlib.font_manager as fm # 设置中文字体 cnfont = fm.FontProperties(fname='/Users/Qiming/Library/Fonts/SimHei.ttf') # 定义绘制图标函数并保存为图片 def chartImg(data={}): group_x = list(data.values()) group_y = list(data.keys()) fig, ax = plt.subplots() # 自定义表格标签及标题样式 plt.title('词频统计表', color='black', fontproperties=cnfont, fontsize=16) ax.set_xlabel('数量', fontproperties=cnfont, color='grey') ax.set_ylabel('词语', fontproperties=cnfont, color='grey') # 绘制图表 ax.set_yticklabels(group_y, fontproperties=cnfont) ax.barh(group_y, group_x) # 保存绘制文件 plt.savefig('chart.png') return 'chart.png'
def configcell_text_and_colors(array_df, lin, col, oText, facecolors, posi, fz, fmt, show_null_values=0): """ config cell text and colors and return text elements to add and to dell @TODO: use fmt """ text_add = [] text_del = [] cell_val = array_df[lin][col] tot_all = array_df[-1][-1] per = (float(cell_val) / tot_all) * 100 curr_column = array_df[:, col] ccl = len(curr_column) #last line and/or last column if (col == (ccl - 1)) or (lin == (ccl - 1)): #tots and percents if (cell_val != 0): if (col == ccl - 1) and (lin == ccl - 1): tot_rig = 0 for i in range(array_df.shape[0] - 1): tot_rig += array_df[i][i] per_ok = (float(tot_rig) / cell_val) * 100 elif (col == ccl - 1): tot_rig = array_df[lin][lin] per_ok = (float(tot_rig) / cell_val) * 100 elif (lin == ccl - 1): tot_rig = array_df[col][col] per_ok = (float(tot_rig) / cell_val) * 100 per_err = 100 - per_ok else: per_ok = per_err = 0 #per_ok_s = ['%.1f%%'%(per_ok), '100%'] [per_ok == 100] per_ok_s = ['%.1f' % (per_ok)][per_ok == 100] #print(['%.1f'%(per_ok)] [per_ok == 100]) #text to DEL text_del.append(oText) #text to ADD font_prop = fm.FontProperties(size=fz) #weight='bold', text_kwargs = dict(color='k', ha="center", va="center", gid='sum', fontproperties=font_prop) #lis_txt = ['%d'%(cell_val), per_ok_s, '%.1f%%'%(per_err)] #lis_txt = ['%d' % (cell_val), per_ok_s] lis_txt = [per_ok_s] print(lis_txt) lis_kwa = [text_kwargs] dic = text_kwargs.copy() dic['color'] = 'dodgerblue' lis_kwa.append(dic) dic = text_kwargs.copy() dic['color'] = 'r' lis_kwa.append(dic) #lis_pos = [(oText._x, oText._y-0.3), (oText._x, oText._y), (oText._x, oText._y+0.3)] #lis_pos = [(oText._x, oText._y - 0.2), (oText._x, oText._y + 0.2)] lis_pos = [(oText._x, oText._y), (oText._x, oText._y)] for i in range(len(lis_txt)): newText = dict(x=lis_pos[i][0], y=lis_pos[i][1], text=lis_txt[i], kw=lis_kwa[i]) #print 'lin: %s, col: %s, newText: %s' %(lin, col, newText) text_add.append(newText) #print '\n' #set background color for sum cells (last line and last column) carr = [0.8, 0.8, 0.8, 1.0] #carr = [0.27, 0.30, 0.27, 1.0] #if(col == ccl - 1) and (lin == ccl - 1): # carr = [0.17, 0.20, 0.17, 1.0] facecolors[posi] = carr else: if (per > 0): txt = '%s\n%.1f%%' % (cell_val, per) else: if (show_null_values == 0): txt = '' elif (show_null_values == 1): txt = '0' else: txt = '0\n0.0%' #oText.set_text(txt) #main diagonal if (col == lin): #set color of the textin the diagonal to white oText.set_color('k') # set background color in the diagonal to blue # facecolors[posi] = [0.35, 0.8, 0.55, 1.0] else: oText.set_color('r') return text_add, text_del
# -*- coding:utf-8 -*- import json import numpy as np import matplotlib.pyplot as plt import matplotlib.font_manager as fm from matplotlib import rc with open('movie.json', 'r', encoding='utf-8') as myFile: data = json.load(myFile) # json --> dict type(사전 자료형) print(data) font_name = fm.FontProperties(fname='c:/Windows/Fonts/H2GTRM.ttf').get_name() rc('font', family=font_name) dataPie = [float(i['book']) for i in data['movie']] print(dataPie) plt.pie(dataPie) category = [i['title'] for i in data['movie']] print(category) plt.legend(category) plt.show()
help="the index of CV ploted, start from 1 ", default=1) parser.add_argument('-time_len', dest='time_len', help="the length of time of each iteration (ns)", default=2) parser.add_argument('-outfile', dest='outfile', help="output file", required=True) arg = parser.parse_args() return arg.infiledir, arg.num_iter, arg.num_walkers, arg.cv_index, arg.time_len, arg.outfile font_path = '/home/dongdong/tigress/calibribold.ttf' font_prop = font_manager.FontProperties(fname=font_path, size=19) leg_prop = font_manager.FontProperties(fname=font_path, size=17) def plot_iter(filedir, num_iter, num_walkers, cv_index, time_len, figout): colors = pl.cm.jet(np.linspace(0, 1, num_walkers)) fig = plt.figure(figsize=(10, 8)) for wal in range(int(num_walkers)): walker_name = '%03d' % wal all_cv = [] all_time = [] for it in range(int(num_iter)): iteration = "%06d" % it filename = filedir + "iter." + str( iteration) + "/00.enhcMD/" + str(walker_name) + "/plm.out" data = np.loadtxt(filename)
import obs_calc.i_fh__calc import obs_calc.b_xyz import obs_calc_analytical.bc_wire_dc from matplotlib import rc, font_manager sizeOfFont = 12 fontProperties = { 'family': 'sans-serif', 'sans-serif': ['Helvetica'], 'weight': 'normal', 'size': sizeOfFont } ticks_font = font_manager.FontProperties(family='Helvetica', style='normal', size=sizeOfFont, weight='normal', stretch='normal') rc('text', usetex=True) rc('font', **fontProperties) def b_wire_comp_plot(xyz0_proj_re, xyz0_proj_im, params): """Very dirty, UNFINISHED function that plots analytic and numeric results from the Ferreira paper, still errors! need to finish! normalization of analytic result by total current through wire is missing only real part of FT is plotted, connection to FH result unclear factor of pi from FT not included/unclear """ ro_t, ri_t, flen, node_dens, sigma, mu_0, mu_r, freq = params # unpack params
def frames(t_arr, a_arr, dtheta=1.0, pixres=1080, \ froot="/Users/salvesen/outreach/asom/expansion/results/frames/expansion", \ rroot="/Users/salvesen/outreach/asom/expansion/results/frames/cmb"): ''' Purpose: -------- Plot every frame for the movie. Inputs: ------- t_arr - Array of times [Gyr] a_arr - Array of scale factors/sizes [-] dtheta - Incremental rotation angle for the CMB sphere between frames [degrees/frame] pixres - Image resolution (240p, 360p, 480p, 720p, 1080p, etc.) froot - Root name for the output frame PNG files rroot - Root name for the output rendered ('r') PNG files ''' # Plotting preferences fres = pixres / 1080.0 dpi = 200 lw = 2.0 * fres fsL = 48 * fres fsS = 24 * fres fsXS = 12 * fres mscl = 24 * fres left, right, bottom, top = 0.0, 1.0, 0.0, 1.0 xsize, ysize = XYsize(pixres=pixres, dpi=dpi) plt.rcParams['axes.linewidth'] = lw plt.rcParams['axes.facecolor'] = 'k' plt.rcParams['axes.titlepad'] = -1.5 * fsS # Fonts jsansR = fm.FontProperties(fname='../fonts/JosefinSans-Regular.ttf') jsansB = fm.FontProperties(fname='../fonts/JosefinSans-Bold.ttf') jsansSB = fm.FontProperties(fname='../fonts/JosefinSans-SemiBold.ttf') jsansBI = fm.FontProperties(fname='../fonts/JosefinSans-BoldItalic.ttf') # Initialize the figure and do various aesthetic things fig = plt.figure(figsize=(xsize, ysize), dpi=dpi) fig.subplots_adjust(left=left, right=right, bottom=bottom, top=top) ax = fig.add_subplot(111) ax.set_aspect("equal") ax.grid(False) ax.set_title("The Universe", fontsize=fsL, fontproperties=jsansB, color='w') # Get rid of the ticks ax.set_xticks([]) ax.set_yticks([]) # Draw lines/vectors to show the scale of the Universe (i.e., plotted sphere) propsTop = dict(mutation_scale=1, lw=lw, linestyle='solid', arrowstyle="-", color='w') propsBot = dict(mutation_scale=1, lw=lw, linestyle='solid', arrowstyle="-", color='w') propsVert = dict(mutation_scale=mscl, lw=lw, linestyle='solid', arrowstyle="<|-|>", color='w') ax.annotate('', xy=(0.500, 0.754), xytext=(0.717, 0.800), xycoords='figure fraction', arrowprops=propsTop) ax.annotate('', xy=(0.611, 0.312), xytext=(0.707, 0.337), xycoords='figure fraction', arrowprops=propsBot) ax.annotate('', xy=(0.707, 0.337), xytext=(0.717, 0.800), xycoords='figure fraction', arrowprops=propsVert) # Print static text onto the figure textLtop = "The TIME is..." ax.annotate(textLtop, (0.15, 0.675), xycoords='figure fraction', fontsize=fsS, color='w', ha='center', va='center', fontproperties=jsansSB) textRtop = "The SIZE is..." ax.annotate(textRtop, (0.85, 0.675), xycoords='figure fraction', fontsize=fsS, color='w', ha='center', va='center', fontproperties=jsansSB) # Print the AstroSoM title and web address on the figure emDash = u'\u2014' textASOM = "Astronomy Sound of the Month" + "\n" + emDash + " AstroSoM.com " + emDash ax.text(0.5, 0.075, textASOM, fontsize=fsXS, color='w', ha='center', va='center', transform=ax.transAxes, fontproperties=jsansR) #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # NOTE: Yes, I am repeating this twice, which is not good code practice or whatever. # But it gets the job done right now and I could clean it up by making a class later. # Set the starting azimuth and elevation azim0 = 0.0 # [degrees] elev0 = 60.0 # [degrees] # We will loop through each time/size in a smart way... # ...output entire set of frames where the CMB sphere has a given azimuthal angle N = len(t_arr) Nz = np.ceil(np.log10(N)).astype(int) N_arr = np.arange(N) azim_arr = np.empty(N) rout_list = [] fout_list = [] for i in N_arr: # Calculate the azimuthal angle for frame i [0,360] azim = azim0 + i * dtheta while (azim >= 360.0): azim = azim - 360.0 azim_arr[i] = azim # Calculate the output file name for rendering i rout_list.append(rroot + "_" + str(i).zfill(Nz) + ".png") # Calculate the output file name for frame i fout_list.append(froot + "_" + str(i).zfill(Nz) + ".png") # Sort the indexing array by azimuthal angle of the CMB sphere rendering # NOTE: kind='mergesort' does exactly what I want! :) isort = np.argsort(azim_arr, kind='mergesort') N_sort = N_arr[isort] #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # Create each individual frame, taking advantage of multiple frames having the same azimuthal angle print("\nCreating individual frames...\n") icnt = 1 pctComplete = 0 dummy = -1.0 * dtheta azim_old = dummy for i in N_sort: # Check if the previous frame has a different azimuthal angle from the current frame # (Hacky if statement to replace "if (azim_now != azim_old)", which is not reliable) azim_now = azim_arr[i] if (np.abs(azim_now - azim_old) > 0.5 * dtheta): # Remove the old CMB sphere (unless one has not been rendered yet) if (azim_old != dummy): imcmb.remove() # Display the new CMB sphere on the 2D plot cmb = image.imread(rout_list[i]) imcmb = ax.imshow(cmb) # Update azim_old azim_old = azim_now # Convert the current time and size to a string (rounding down) tnow = t_arr[i] anow = a_arr[i] # Print the time and size on the figure textLbot = timestr(tnow) textRbot = sizestr(anow) ttxt = ax.annotate(textLbot, (0.15, 0.5), xycoords='figure fraction', fontsize=fsS, color='w', ha='center', va='center', fontproperties=jsansR) atxt = ax.annotate(textRbot, (0.85, 0.5), xycoords='figure fraction', fontsize=fsS, color='w', ha='center', va='center', fontproperties=jsansR) # Save the figure fout = fout_list[i] fig.savefig(fout, facecolor=fig.get_facecolor(), edgecolor='none', dpi=dpi) # Remove the current time/size text output ttxt.remove() atxt.remove() # Give a progress report every so often if ((icnt % 100) == 0): pctComplete = float(icnt) / float(N) * 100 print " % Complete: ", '{:.1f}'.format(pctComplete) icnt = icnt + 1 # Close the plot object plt.close()
import numpy as np import matplotlib.pyplot as plt import matplotlib.font_manager as font_manager import requests #TODO: set figure size larger, axes bigger, better spacing, changing x intervals #TODO: port to js (hopefully some easier more powerful graphing libraries) #font size larger, window needs to be rescaled with cursor once started font_prop = font_manager.FontProperties(size=20) # get json from coin market cap for top 3 most capitalized currencies # 1) xbt # 2) eth # 3) xrp url = 'https://api.coinmarketcap.com/v1/ticker/?convert=USD&limit=3' # (not very important for now) todo: pull these value directly from kraken wallet amt_xbt = 0.00330 amt_xrp = 600 plt.axis([0, 1000, 21, 25], FontProperties=font_prop) plt.title('Live Wallet USD Value', FontProperties=font_prop) plt.xlabel('Time (5 sec intervals)', FontProperties=font_prop) plt.ylabel('Total $USD Value of Crypto Wallet', FontProperties=font_prop) plt.ion() for i in range(1000): #pull response response = requests.get(url) data = response.json()
#思想,由于活动随着时间的增加,进货金额在增加,所以物品的单价*进货量一定在增加,那么横坐标是单价,纵坐标是进货量的散点图一定有什么规律,试试。 import pandas as pd import numpy as np from matplotlib import font_manager from matplotlib import pyplot as plt fig, ax = plt.subplots() my_font =font_manager.FontProperties(fname="/usr/share/fonts/truetype/wqy/wqy-microhei.ttc") from sklearn.neighbors import KNeighborsClassifier#导入写好的knn的库 All=pd.read_excel('/home/haoge/桌面/500GB/备份/文档/数据分析/实训耗材数据/数据分析excel表/采购入库信息_20191224202718.xls') #==============================处理数据================== All['入库仓库']=All['入库仓库'].apply(lambda a:a[:2])#仓库名称切片 All['制单时间']=All['制单时间'].apply(lambda b:b[5:10])#制单时间切片 Allname=All['单据名称'].unique() name_ck=All['入库仓库'] time_zd=All['制单时间'] All['制单时间'] = All['制单时间'] .map(lambda y: y[:2]).astype('int') + 0.01 * All['制单时间'] .map(lambda y: y[-2:]).astype('int') # 1.1:1月1号 make_time=All['制单时间'] into_cage=All['入库仓库'] j=0 into_cage_index=np.array(['YW', 'SX', 'HH', 'TY', 'DZ', 'JX', 'QC', 'YS', 'XX', 'JS']) for i in into_cage.unique(): into_cage[into_cage==i]=j j=j+1 #========================================预处理,把时间变数字,把仓库名称变数字 x_dataname=[] #标签名 y_data=[] #标签名对应数据 for i in Allname: if All[All['单据名称']==i].count()[0]>10: Into_cage_one=All[All['单据名称']==i]['入库仓库'] into_Time=All[All['单据名称']==i]['制单时间']
- 如何设置图片的大小; - 如何保存到本地; - x轴和y轴的描述信息; - 中文显示乱码问题; - 调整x轴和y轴的刻度; - x轴的刻度信息过长, 如何调整? - 标记最高点; """ # 案例1: 假设一天中每隔两个小时气温变化的折线图绘制; from matplotlib import pyplot as plt from matplotlib import font_manager # 4). 中文显示乱码问题; myfont = font_manager.FontProperties( fname="/usr/share/fonts/cjkuni-uming/uming.ttc", size=18) titlefont = font_manager.FontProperties( fname="/usr/share/fonts/cjkuni-uming/uming.ttc", size=24) # 图表的x轴的数据, 是一个可迭代的数据类型 x_times = range(0, 24, 2) # 图表的y轴的数据, 是一个可迭代的数据类型 y_temp = [15, 12, 13, 20, 23, 30, 15, 12, 13, 20, 23, 30] # min(y_temp), max(y_temp) # 1). 如何设置图片的大小; plt.figure(figsize=(10, 10)) # 传入x和y轴的数据, 绘制图形; plt.plot(x_times, y_temp)
# Defines a function that implement an algorithm for mathing template to a timeseries to detect iGluSNFR responses import numpy as np import pandas as pd from matplotlib import pyplot as plt import matplotlib.font_manager as font_manager import math from scipy import optimize from scipy.optimize import minimize from scipy.signal import butter, lfilter, freqz, detrend import re import os font_path = '/home/anup/.matplotlib/fonts/arial.ttf' fontprop = font_manager.FontProperties(fname=font_path, size=18) def background_subtract(t, f, tstim0, tpre=0): # t: time, f: raw fluorescence, tpre: time from start for background substraction # print(t,f,tpre) f = f + min(f) itstim0 = np.where(t > tstim0)[0][0] - 1 itpre = np.where(t > tpre)[0][0] - 1 baseline = np.mean(f[min(itstim0, itpre):max(itpre, itstim0)]) # print('baseline: ',baseline) return ((baseline - f) / baseline) def smooth(y, windowlen=3, window='hanning'): s = np.concatenate([y[windowlen - 1:0:-1], y, y[-2:-windowlen - 1:-1]]) if (window == 'flat'): w = np.ones(windowlen, dtype='double')
def clabel(self, *args, **kwargs): """ clabel(CS, **kwargs) - add labels to line contours in CS, where CS is a ContourSet object returned by contour. clabel(CS, V, **kwargs) - only label contours listed in V keyword arguments: * fontsize = None: as described in http://matplotlib.sf.net/fonts.html * colors = None: - a tuple of matplotlib color args (string, float, rgb, etc), different labels will be plotted in different colors in the order specified - one string color, e.g. colors = 'r' or colors = 'red', all labels will be plotted in this color - if colors == None, the color of each label matches the color of the corresponding contour * inline = True: controls whether the underlying contour is removed (inline = True) or not (False) * fmt = '%1.3f': a format string for the label """ fontsize = kwargs.get('fontsize', None) inline = kwargs.get('inline', 1) self.fmt = kwargs.get('fmt', '%1.3f') _colors = kwargs.get('colors', None) if len(args) == 0: levels = self.levels indices = range(len(self.levels)) elif len(args) == 1: levlabs = list(args[0]) indices, levels = [], [] for i, lev in enumerate(self.levels): if lev in levlabs: indices.append(i) levels.append(lev) if len(levels) < len(levlabs): msg = "Specified levels " + str(levlabs) msg += "\n don't match available levels " msg += str(self.levels) raise ValueError(msg) else: raise TypeError("Illegal arguments to clabel, see help(clabel)") self.label_levels = levels self.label_indices = indices self.fp = font_manager.FontProperties() if fontsize == None: font_size = int(self.fp.get_size_in_points()) else: if type(fontsize) not in [int, float, str]: raise TypeError("Font size must be an integer number.") # Can't it be floating point, as indicated in line above? else: if type(fontsize) == str: font_size = int(self.fp.get_size_in_points()) else: self.fp.set_size(fontsize) font_size = fontsize self.fslist = [font_size] * len(levels) if _colors == None: self.label_mappable = self self.label_cvalues = npy.take(self.cvalues, self.label_indices) else: cmap = colors.ListedColormap(_colors, N=len(self.label_levels)) self.label_cvalues = range(len(self.label_levels)) self.label_mappable = cm.ScalarMappable(cmap=cmap, norm=colors.NoNorm()) #self.cl = [] # Initialized in ContourSet.__init__ #self.cl_cvalues = [] # same self.cl_xy = [] self.labels(inline) for label in self.cl: self.ax.add_artist(label) self.label_list = cbook.silent_list('text.Text', self.cl) return self.label_list
file.close() # In[5]: # T-SNE 사용 (고차원을 저차원으로 표현해주는 그래프) from sklearn.manifold import TSNE from matplotlib import font_manager, rc import matplotlib as mpl import matplotlib.pyplot as plt import gensim.models as g import matplotlib.font_manager as fm # 한국어 깨짐 방지 위해 한국어 폰트 설정 font_location = 'C:\Windows\\Fonts\\batang.ttc' font_name = font_manager.FontProperties(fname=font_location).get_name() rc('font', family=font_name) # 글자 깨짐 방지 mpl.rcParams['axes.unicode_minus'] = False store_model = g.Doc2Vec.load('CBOWFile') vocab = list(store_model.wv.vocab) X = store_model[vocab] # 이차원 그래프로 표현 tsne = TSNE(n_components=2) X_tsne = tsne.fit_transform(X) #print(len(X_tsne)) # 표 그리기
import re from soynlp.tokenizer import RegexTokenizer from soynlp.noun import LRNounExtractor from collections import Counter from wordcloud import WordCloud import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.font_manager as fm from stopwords import make_stopword # 마이너스 폰트 깨짐 현상 수정 mpl.rcParams['axes.unicode_minus'] = False # 한글 폰트 설정 path = 'C:/Users/admin/AppData/Local/Microsoft/Windows/Fonts/D2Coding.ttf' font_name = fm.FontProperties(fname=path, size=15).get_name() plt.rc('font', family=font_name) # 텍스트 데이터 전처리 def preprocessing(text): # 개행문자 제거 text = re.sub('\\\\n', ' ', text) # 【피 고 인】형식 문자 제거 text = re.sub(r'\【[^)]*\】', '', text) # 양 끝 공백 제거 text = text.strip()
x = [] for i in range(0, len(datelist)): if i % 3 != 0: x.append('') else: x.append(datelist[i]) rankdict = {} for rankitem in ranklist['data']: if rankitem['name'] not in rankdict: rankdict[rankitem['name']] = rankitem['confirmAdd'] #print(rankdict) rankdict = sorted(rankdict.items(), key=lambda asd:asd[1], reverse=True) #print(rankdict) myfont = fm.FontProperties(fname='kaiti.ttf') myColor = ['#000000', '#FF0000', '#00FF00', '#0000FF', '#00FFFF', '#FF00FF', '#FFFF00', '#808080'] i = 0 flag = False ylimit = 0 for rankitem in rankdict: print(rankitem[0]) if i % 8 == 0: fig = plt.figure(figsize=(12, 8)) ax = fig.add_subplot(111) plt.title('新冠新增确诊', fontproperties=myfont, fontsize=16) plt.xlim((0, len(x))) plt.xticks(np.linspace(0, len(x), len(x) + 1)) ax.set_xticklabels(x, rotation=0, fontsize='small') plt.xlabel('日期', fontproperties=myfont, fontsize=16)
#!/usr/bin/env python # coding: utf-8 import sys import warnings warnings.filterwarnings(action='ignore') import collections from IPython.display import display from IPython.display import Image import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl from matplotlib import font_manager, rc import pandas as pd import mglearn from sklearn.model_selection import train_test_split mpl.rcParams['axes.unicode_minus'] = False font_fname = 'fonts/NanumGothic.ttf' font_name = font_manager.FontProperties(fname=font_fname).get_name() rc('font', family=font_name) # size, family print('font size : ' + str(plt.rcParams['font.size'])) print('font family : ' + str(plt.rcParams['font.family'])) # import default setting print( 'python version : {0}\npandas version : {1}\nmatplotlib version : {2}\nnumpy version : {3}\n' .format(sys.version, pd.__version__, mpl.__version__, np.__version__))
def plotParticleDataHistory(self, propertyName, title, outputFolder, filename, extension, xAxisLabel, yAxisLabel, component=0): timeVector = list(self.time.values()) particleData = self.particleData if component == 'X': component = 0 elif component == 'Y': component = 1 elif component == 'Z': component = 2 fig = plt.figure(figsize=(18, 14), facecolor='w', edgecolor='k') ax = fig.add_subplot(111) xMinimum = min(timeVector) xMaximum = max(timeVector) yMinimum = min([ propertyValue for particleType in particleData.values() for particle in particleType.values() for propertyValue in particle[propertyName].values() ]) yMaximum = max([ propertyValue for particleType in particleData.values() for particle in particleType.values() for propertyValue in particle[propertyName].values() ]) total = [ sum(history) for history in zip(*[ particle[propertyName].values() for particleType in particleData.values() for particle in particleType.values() ]) ] print("property name: ", propertyName) yMinimum = min(min(total), yMinimum) yMaximum = max(max(total), yMaximum) xWidth = xMaximum - xMinimum yWidth = yMaximum - yMinimum # Set labels ax.set_xlabel(xAxisLabel, size=24, weight='normal', family='sans-serif') ax.set_ylabel(yAxisLabel, size=24, weight='normal', family='sans-serif') # ax.set_title(title, size=30, weight='normal', family='sans-serif') # Set plot limits xMinimumLim = xMinimum # - 0.1*xWidth xMaximumLim = xMaximum # + 0.1*xWidth yMinimumLim = yMinimum - 0.1 * yWidth yMaximumLim = yMaximum + 0.1 * yWidth plt.xlim(xMinimumLim, xMaximumLim) plt.ylim(yMinimumLim, yMaximumLim) # Set plot ticks ax.tick_params() ax.minorticks_on() # rangeStep = numpy.round(xWidth , int( numpy.abs(numpy.log10(xWidth)) + 1 ) ) # xTicks = numpy.linspace(start=xMinimum , stop=xMaximum , num=10) # yTicks = numpy.linspace(start=yMinimum , stop=yMaximum , num=20) # # ax.set_xticks( xTicks ) # ax.set_yticks( yTicks ) # Add grid ax.grid(visible=True, which='major') ax.grid(visible=True, which='minor', color=[0.5, 0.5, 0.5]) ax.title.set_fontsize(25) for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontproperties( font_manager.FontProperties(family='sans-serif', style='normal', size=15, weight='normal')) # Plot total propertyName-property ax.plot(timeVector, total, 'k-', linewidth=2.0, label="Total") # Plot each particle's property for particleTypename, particleType in particleData.items(): for particleName, particle in particleType.items(): ax.plot([self.time[t] for t in self.time.keys()], [particle[propertyName][t] for t in self.time.keys()], color=getColor(particle["Color"][next( iter(particle["Color"]))]), label=particleName, marker='.') handles, labels = ax.get_legend_handles_labels() handle_list, label_list = [], [] for handle, label in zip(handles, labels): if label not in label_list: handle_list.append(handle) label_list.append(label) lgd = ax.legend(handle_list, label_list, loc='best', prop={ 'size': 15, 'family': 'sans-serif', 'weight': 'normal' }) lgd.set_title("Legenda", prop={ 'size': 18, 'family': 'sans-serif', 'weight': 'normal' }) plt.savefig(os.path.join(outputFolder, filename + extension), bbox_inches="tight") plt.close(fig)