1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
| ax.set_ylabel(u'Temperature (\N{DEGREE SIGN}C)', fontweight='bold')
from mpl_toolkits.axes_grid1 import make_axes_locatable divider = make_axes_locatable(ax1) cax = divider.append_axes("right", size="5%", pad=0.1) cbar = plt.colorbar(cf, cax=cax) cbarlabel = "xxxx" cbar.ax.set_xlabel(cbarlabel,size = 8,labelpad=-35)
cbaxes = fig.add_axes([0.83, 0.125, 0.1, 0.01]) cbar = plt.colorbar(ss,cax=cbaxes,orientation='horizontal') loc_ = np.array([5,10,15,20,25]) cbar.set_ticks(loc_) cbar.set_ticklabels(loc_)
(1) cbar.ax.tick_params(labelsize=8) (2) cbar.ax.set_xticklabels(cbar.ax.get_xticklabels(), fontsize=8) cbar.ax.set_xlabel(r'$\mathregular{OC/EC}$',fontsize = 8,labelpad = -28)
from matplotlib.font_manager import FontProperties mpl.rcParams['font.sans-serif'] = ['Microsoft YaHei'] plt.rcParams['axes.unicode_minus'] = False
def stylize_axes(ax): ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.xaxis.set_tick_params(top='off', direction='out', width=1) ax.yaxis.set_tick_params(right='off', direction='out', width=1)
from scipy import stats slope, intercept, r_value, p_value, slope_std_error = stats.linregress(x, y) xx = np.arange(x.min(),x,max(),0.01) yy = slope*xx+intercept clabel = plt.plot(xx,yy,color ='k', lw =1.2, linestyle = "-", label = clabel)
def get_aspect(ax): xlim = ax.get_xlim() ylim = ax.get_ylim() aspect_ratio = abs((ylim[0]-ylim[1]) / (xlim[0]-xlim[1])) return aspect_ratio fig = plt.figure(figsize=(12,8)) ax1=plt.subplot(121, projection=ccrs.PlateCarree()) ax2=plt.subplot(122) ax2.set_aspect(get_aspect(ax1) / get_aspect(ax2))
for area in [100, 300, 500]: plt.scatter([], [], c='k', alpha=0.3, s=area, label=str(area) + ' km$^2$') plt.legend(scatterpoints=1, frameon=False, labelspacing=1, title='City Area')
ax.tick_params(axis=u'both', which=u'both',length=0)
fig = plt.figure(figsize=(7,4))
left, width = 0.07, 0.6 bottom, height = 0.1, .8 bottom_h = left_h = left+width+0.05 rect_cones = [left, bottom, width, height] rect_box = [left_h, bottom, 0.5, height] ax1 = plt.axes(rect_cones,projection=ccrs.PlateCarree()) ax2 = plt.axes(rect_box) ax2.set_aspect(get_aspect(ax1) / get_aspect(ax2))
def plot_legend(title): s = [1,3,5,7,9] c = plt.cm.binary(np.arange(5)/5.0) labels =['A',"B",'C',"D","E"] cir1 = plt.scatter([1], [2], c=c[0], alpha=0.8, s=s[0],label=r'<0.5') cir2 = plt.scatter([1], [2], c=c[1], alpha=0.8, s=s[1],label=labels[1]) cir3 = plt.scatter([1], [2], c=c[2], alpha=0.8, s=s[2],label=labels[2]) cir4 = plt.scatter([1], [2], c=c[3], alpha=0.8, s=s[3],label=labels[3]) cir5 = plt.scatter([1], [2], c=c[4], alpha=0.8, s=s[4],label=labels[4]) leg = plt.legend([cir1,cir2,cir3,cir4,cir5],labels,scatterpoints = 1, \ frameon=False, labelspacing=0.9, ncol =2, fontsize=8,title=title , loc = [0.05,0.1])
c_list = plt.cm.rainbow(np.arange(6)/6.0)
axu = ax.twinx() axu.spines["right"].set_position(("axes", 1.25)) so_,=plt.plot(xxx) axu.yaxis.label.set_color(so_.get_color()) axu.spines['right'].set_color(so_.get_color()) axu.spines["right"].set_edgecolor(so_.get_color()) axu.tick_params(axis='y', colors=so_.get_color())
from matplotlib.patches import Rectangle import matplotlib.patches as mpatches rec = mpatches.Rectangle((position[i]- width/2.0,bot_[i]),width,hei_[i],linewidth=1,edgecolor='b',facecolor='none',zorder=12) ax.add_patch(rec)
def make_rgb_transparent(rgb, bg_rgb, alpha): return [alpha * c1 + (1 - alpha) * c2 for (c1, c2) in zip(rgb, bg_rgb)] from matplotlib import colors import matplotlib.pyplot as plt
alpha = 0.5
kwargs = dict(edgecolors='none', s=3900, marker='s') for i, color in enumerate(['red', 'blue', 'green']): rgb = colors.colorConverter.to_rgb(color) rgb_new = make_rgb_transparent(rgb, (1, 1, 1), alpha) print(color, rgb, rgb_new) plt.scatter([i], [0], color=color, **kwargs) plt.scatter([i], [1], color=color, alpha=alpha, **kwargs) plt.scatter([i], [2], color=rgb_new, **kwargs)
def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100): new_cmap = colors.LinearSegmentedColormap.from_list( 'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval), cmap(np.linspace(minval, maxval, n))) return new_cmap cmap = plt.get_cmap('terrain') terrain_cmap = truncate_colormap(cmap, 0.15, 0.9)
import matplotlib.gridspec as gridspec fig = plt.figure(figsize=(9,6)) gs = gridspec.GridSpec(46,1) row_xx = 23
ax1 = plt.subplot(gs[0:row_xx, 0])
lines, labels = ax.get_legend_handles_labels() lines2, labels2 = ax2.get_legend_handles_labels() ax2.legend(lines + lines2, labels + labels2, loc=0)
ax.set_xticks([0, 60, 120, 180, 240, 300, 360], crs=ccrs.PlateCarree())d ax.set_yticks([-90, -60, -30, 0, 30, 60, 90], crs=ccrs.PlateCarree()) lon_formatter = LongitudeFormatter(zero_direction_label=True) lat_formatter = LatitudeFormatter() ax.xaxis.set_major_formatter(lon_formatter) ax.yaxis.set_major_formatter(lat_formatter)
ax.set_xticks(np.arange(extent[0]+2, extent[1]+2, 15), crs=ccrs.PlateCarree()) ax.set_yticks(np.arange(extent[2]+3, extent[3], 15), crs=ccrs.PlateCarree()) ax.set_xticklabels([r'$\mathrm{75^o E}$',r'$\mathrm{90^o E}$',r'$\mathrm{105^o E}$',\ r'$\mathrm{120^o E}$',r'$\mathrm{135^o E}$',]) ax.set_yticklabels([r'$\mathrm{20^o N}$',r'$\mathrm{35^o N}$',r'$\mathrm{50^o N}$'])
from matplotlib.axes import Axes from cartopy.mpl.geoaxes import GeoAxes GeoAxes._pcolormesh_patched = Axes.pcolormesh
import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties
song_ti = FontProperties(fname=r'/Library/Fonts/Songti.ttc', size=20) times_new_roman = FontProperties(fname=r'/Library/Fonts/Arial Black.ttf', size=15) ax = plt.gca() ax.set_title(u'能量随时间的变化', fontproperties=song_ti) ax.set_xlabel('Time (s)', fontproperties=times_new_roman) ax.set_ylabel('Energy (J)', fontproperties=times_new_roman) plt.show()
(label='_nolegend_')
ax.set_facecolor("#F5F5F5")
import matplotlib.colors as colors
class MidpointNormalize(colors.Normalize): def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False): self.midpoint = midpoint colors.Normalize.__init__(self, vmin, vmax, clip)
def __call__(self, value, clip=None): x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1] return np.ma.masked_array(np.interp(value, x, y))
cbaxes = fig.add_axes([0.29, 0.27, 0.18, 0.02]) cbar = plt.colorbar(ss,cax=cbaxes, orientation='horizontal') n = 6 st_po = [] for i in range(0,n,1): st_po.append(np.array_split(pd.to_datetime(sorted(date_point)),n)[i].values[0]) cb_ticks = [float(c) for c in st_po] cbar.ax.set_xticklabels(pd.to_datetime(cb_ticks).strftime('%b')) cbar.ax.tick_params(labelsize=8.5)
import nclcmaps nclcmaps.cmaps("precip2_17lev")
cm = LinearSegmentedColormap.from_list('test',plt.cm.BuPu(np.arange(6)/6.0)[1:], N=5)
http://chris35wills.github.io/discrete_colourbar/
from matplotlib.ticker import StrMethodFormatter, NullFormatter ax.yaxis.set_major_formatter(StrMethodFormatter('{x:.3f}')) ax.yaxis.set_minor_formatter(NullFormatter())
fig, axs = plt.subplots(2,4, figsize=(15, 6), facecolor='w', edgecolor='k') fig.subplots_adjust(hspace = .5, wspace=.001) axs = axs.ravel()
for i in range(8):
axs[i].contourf(np.random.rand(10,10),5,cmap=plt.cm.Oranges) axs[i].set_title(str(250+i))
from matplotlib.collections import PatchCollection from matplotlib.patches import Rectangle def PATCH_BOX(ax,pos,wid): for x in pos[::2]: width = wid/2.0 facecolor = "#F0F0F0" rect = Rectangle((x-width, 0.00), width*4.0,1000000,facecolor=facecolor,linewidth = 0) ax.add_patch(rect)
https://github.com/SciTools/cartopy/issues/837 pip uninstall shapely && pip install --no-binary :all: shapely
pip uninstall shapely & pip install shapely --no-binary shapely==1.7a2
linewidths=1
from matplotlib import cm cs=cm.Set2(np.arange(4)/4.)
ax.plot(0.3,-0.1 , 'ro', fillstyle='full', markersize=5, transform=ax.transAxes,clip_on =False)
import matplotlib.dates as mdates
fig1 = plt.figure(figsize=(5, 5)) ax1 = fig1.add_subplot()
date_point = df['Date'] ss1 = ax1.scatter(df['WSOC'], df['OC'], c=mdates.date2num(date_point), cmap=plt.cm.coolwarm, s=100) cbaxes1 = fig1.add_axes([0.29, 0.27, 0.48, 0.02]) cb1 = plt.colorbar(ss1, cax=cbaxes1, orientation='horizontal') loc1 = mdates.AutoDateLocator(maxticks=12) cb1.ax.xaxis.set_major_locator(loc1) cb1.ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(loc1))
fig2 = plt.figure(figsize=(5, 5)) ax2 = fig2.add_subplot()
date_point = df['Date'] ss2 = ax2.scatter(df['WSOC'], df['OC'], c=date_point, cmap=plt.cm.coolwarm, s=100)
cbaxes2 = fig2.add_axes([0.29, 0.27, 0.48, 0.02]) cbar2 = plt.colorbar(ss2, cax=cbaxes2, orientation='horizontal')
n = 5 st_po = [] for i in range(0, n, 1): st_po.append(np.array_split(pd.to_datetime(sorted(date_point)), n)[i].values[0])
cb_ticks = [float(c) for c in st_po] cbar2.ax.set_xticklabels(pd.to_datetime(cb_ticks).strftime('%b')) cbar2.ax.tick_params(labelsize=8.5)
from matplotlib.colors import ListedColormap import matplotlib as mpl
fig = plt.subplots(figsize=(10,2)) ax = plt.subplot(111) color_list = ['#cccccc', '#da6701','#00994d','#00cccc', '#0000ff','#000099','#c9ace6','#9039e6','#000000'] cmap_diy = ListedColormap(color_list, color_list) col_map = cmap_diy new_val = [] ticks = np.linspace(0.0,1, len(color_list)+1) for i in range(0,len(ticks)-1,1): new_val.append((ticks[i]+ticks[i+1])/2.0) cbar = mpl.colorbar.ColorbarBase(ax, cmap=col_map, orientation = 'horizontal', ticks =new_val, alpha = 0.75) cbar.ax.set_xticklabels(color_list, fontsize =12, rotation = 30) ttl = plt.title('EESI Color Palette 1',fontweight="bold",fontsize =18,) ttl.set_position([.5, 1.15]) plt.tight_layout()
def box_plot(ax, data, pos, color): bp = ax.boxplot(data, sym='', whis=[5, 95], widths=(len(data) + 4) / (2 * len(data)) * 0.7, positions=pos, boxprops=dict(facecolor=color, edgecolor=color), medianprops=dict(color='k'), whiskerprops=dict(color='k'), capprops=dict(color='k'), patch_artist=True) for box in bp['boxes']: box.set(facecolor=color) return bp
import stats mask = ~np.isnan(x) & ~np.isnan(y) x_clean = x[mask] y_clean = y[mask]
slope, intercept, r_value, p_value, std_err = stats.linregress(x_clean, y_clean)
fig, ax = plt.subplots() ax.scatter(x_clean, y_clean, s=50, edgecolors='black', alpha=0.8)
ax.plot(x_clean, slope*x_clean + intercept, color='red', linestyle='-', label='Linear Fit')
ax.text(0.05, 0.95, 'y = {:.2f}x + {:.2f}'.format(slope, intercept), transform=ax.transAxes, fontsize=14,horizontalalignment='left',\ verticalalignment='top', bbox=dict(facecolor='white',edgecolor='white', alpha=0.8))
fig = plt.figure(figsize=(12,4)) c_time = mdates.date2num(auto_df_dl['Date']) ss = plt.scatter(pd.to_datetime(auto_df_dl['sample_starting_time']), auto_df_dl['130.15903'], c=c_time,cmap = plt.cm.Spectral_r) cbaxes = fig.add_axes([0.61, 0.75, 0.25,0.02]) cb = plt.colorbar(ss, cax=cbaxes, orientation='horizontal') loc = mdates.AutoDateLocator(maxticks=12) cb.ax.xaxis.set_major_locator(loc) cb.ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(loc))
labels = ["%.2f" % (c) + tof_ion[i] for i, c in enumerate(tof_mz.values)] tooltip = mpld3.plugins.PointLabelTooltip(ax.collections, labels=labels) mpld3.plugins.connect(fig, tooltip)
cbaxes = fig.add_axes([0.775, 0.2, 0.11, 0.015]) ticks = [50,100, 250,500] cbar = plt.colorbar(ss_,ticks =ticks, cax=cbaxes,orientation='horizontal', ) cbar.ax.set_xticks(ticks) cbar.ax.set_xticklabels(tick_labels, fontsize=7) cbar.ax.set_xlabel('FRP (MW)',fontsize = 8, labelpad = -25) cbar.ax.tick_params(color='#FFFFFF', direction='in')
def plot_matrix_dendrogram_cn(corr_,va): D = corr_ ax1 = fig.add_axes([0.9,0.15,0.11,0.7*7/6.0]) Y = sch.linkage(D, method='ward') set_link_color_palette(line_color) with plt.rc_context({'lines.linewidth': 1.25}): Z1 = sch.dendrogram(Y, orientation='right',above_threshold_color='grey', color_threshold=va, ) ax1.set_xticks([]) ax1.set_yticks([]) ax1.axis('off') axmatrix = fig.add_axes([0.05,0.15,0.70,0.7*7/6.0]) idx1 = Z1['leaves'] idx2 = Z1['leaves'] D = D[idx1,:] D = D[:,idx1] mask = np.tri(D.shape[1], k=-1) A = np.ma.array(D, mask=mask) cmap = plt.cm.YlOrRd
cmap.set_over('#C0C1C0') im = axmatrix.matshow(A, aspect='auto', origin='lower', cmap=cmap,vmax = 0.999, )
axmatrix.set_xticks(np.arange(0,len(ele_name),1) - 0.5) site_X = [ele_name[i] for i in idx1] axmatrix.set_xticklabels(site_X, minor=False, va="baseline") axmatrix.xaxis.set_label_position('bottom') axmatrix.xaxis.tick_bottom() pylab.xticks(fontsize=8,) axmatrix.tick_params(axis='x', pad=60,length=0,rotation = 45) axmatrix.tick_params(axis='y', pad=2,length=0)
ind_array = np.arange(0,len(ele_name),1) x, y = np.meshgrid(ind_array, ind_array) for i in range(0,len(ele_name),1): for j in range(0,len(ele_name),1): if math.isnan(A[j,i]) == 0: axmatrix.text(i, j, str(round(A[j,i], 2)), color = 'black',va='center', ha='center', fontsize = 12)
axcolor = fig.add_axes([0.05,0.7,0.2,0.015]) cbar = pylab.colorbar(im, cax=axcolor,orientation='horizontal' ) cbar.set_label(r'$\mathregular{{Pearson^{\prime}}s\ r}$', labelpad = -35, fontsize = 10) loc_ = np.array([0.2,0.5,0.8]) cbar.set_ticks(loc_) ttt = [0.2,0.5,0.8] cbar.set_ticklabels(ttt,) cbar.ax.tick_params(color="w", direction='in',labelsize=10)
axmatrix.set_yticks(range(len(ele_name))) site_Y = [ ele_name[i] for i in idx1] axmatrix.set_yticklabels(site_Y, minor=False, fontsize =8) axmatrix.yaxis.set_label_position('right') axmatrix.yaxis.tick_right() pylab.yticks( fontsize=8) axmatrix.spines['left'].set_visible(False) axmatrix .spines['top'].set_visible(False) def fitting_line(x,y): mask = ~np.isnan(x) & ~np.isnan(y) x_clean = x[mask] y_clean = y[mask]
slope, intercept, r_value, p_value, std_err = stats.linregress(x_clean, y_clean) annotation = f"y = {slope:.2f}x + {intercept:.2f}\n\n" + f"r = {r_value:.2f}" ax.annotate(annotation, xy=(0.05, 0.7), xycoords='axes fraction', fontsize = 10)
list_a,list_b = owb_poa,owb_soa ions_intersection = list_a[list_a['Ion'].isin(list_b['Ion'])]['Ion'].unique() ions_only_a = list_a[~list_a['Ion'].isin(list_b['Ion'])]['Ion'].unique() ions_only_b = list_b[~list_b['Ion'].isin(list_a['Ion'])]['Ion'].unique()
from matplotlib_venn import venn2
num_ions_in_a_not_b = len(ions_only_a) num_ions_in_b_not_a = len(ions_only_b) num_ions_intersection = len(ions_intersection)
plt.figure(figsize=(6, 5)) venn2(subsets=(num_ions_in_a_not_b,num_ions_in_b_not_a, num_ions_intersection), set_labels=('Open wood burning POA','Open wood burning SOA'), set_colors=('#5477b1', '#f5a34f'))
plt.savefig('./Figures/20240423/Orbitrap_fitted_ions_OWB_POA+SOA.png', dpi = 400) plt.tight_layout() plt.show()
def only_in_target(tar,ref1,ref2): list1= (tar[tar['Ion'].isin(ref1['Ion'])]['Ion'].unique()) list2= (tar[tar['Ion'].isin(ref2['Ion'])]['Ion'].unique()) list_tot = np.unique(np.append(list1,list2)) return tar[~tar['Ion'].isin(list_tot)]['Ion'].unique()
ions_intersection_ab = list_a[list_a['Ion'].isin(list_b['Ion'])]['Ion'].unique() ions_intersection_ac = list_a[list_a['Ion'].isin(list_c['Ion'])]['Ion'].unique() ions_intersection_bc = list_b[list_b['Ion'].isin(list_c['Ion'])]['Ion'].unique()
ions_intersection_abc = list_a[list_a['Ion'].isin(ions_intersection_bc)]['Ion'].unique()
ions_only_a = only_in_target(list_a,list_b,list_c) ions_only_b = only_in_target(list_b,list_a,list_c) ions_only_c = only_in_target(list_c,list_a,list_b)
ions_unique_a = np.setdiff1d(ions_only_a, ions_intersection_abc) ions_unique_b = np.setdiff1d(ions_only_b, ions_intersection_abc) ions_unique_c = np.setdiff1d(ions_only_c, ions_intersection_abc)
num_ions_in_a_not_bc = len(ions_unique_a) num_ions_in_b_not_ac = len(ions_unique_b) num_ions_in_c_not_ab = len(ions_unique_c) num_ions_intersection_ab = len(ions_intersection_ab) - len(ions_intersection_abc) num_ions_intersection_ac = len(ions_intersection_ac) - len(ions_intersection_abc) num_ions_intersection_bc = len(ions_intersection_bc) - len(ions_intersection_abc) num_ions_intersection_abc = len(ions_intersection_abc)
from matplotlib_venn import venn3
plt.figure(figsize=(10, 6)) v = venn3(subsets=(num_ions_in_a_not_bc, num_ions_in_b_not_ac, num_ions_intersection_ab, num_ions_in_c_not_ab, num_ions_intersection_ac, num_ions_intersection_bc, num_ions_intersection_abc), set_colors=('#a6cee3', '#d83f3f', '#405f3a'), set_labels=('All samples Merged (2371 ions)', ' Coal burning SOA (616 ions)', ' Open burning SOA (858 ions)'))
for area in v.patches: if area: area.set_edgecolor('k')
plt.tight_layout() plt.savefig("./Figures/20240423/Combined_coal_POA_owb_SOA_All.png", dpi = 400) plt.show()
|
Comments