I want to add a "spheres" to my data cluster - pandas

I want to add a kind of "spheres" to my data cluster.
My data cluster is this, which does not have ""spheres".
And this is my code
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')
import pandas as pd
from sklearn.cluster import KMeans
MY_FILE='total_watt.csv'
date = []
consumption = []
df = pd.read_csv(MY_FILE, parse_dates=[0], index_col=[0])
df = df.resample('1D', how='sum')
df = df.dropna()
date = df.index.tolist()
date = [x.strftime('%Y-%m-%d') for x in date]
from sklearn.preprocessing import LabelEncoder
encoder = LabelEncoder()
date_numeric = encoder.fit_transform(date)
consumption = df[df.columns[0]].values
X = np.array([date_numeric, consumption]).T
kmeans = KMeans(n_clusters=3)
kmeans.fit(X)
centroids = kmeans.cluster_centers_
labels = kmeans.labels_
print(centroids)
print(labels)
fig, ax = plt.subplots(figsize=(10,8))
rect = fig.patch
rect.set_facecolor('#2D2B2B')
colors = ["b.","r.","g."]
for i in range(len(X)):
print("coordinate:",encoder.inverse_transform(X[i,0].astype(int)), X[i,1], "label:", labels[i])
ax.plot(X[i][0], X[i][1], colors[labels[i]], markersize = 10)
ax.scatter(centroids[:, 0],centroids[:, 1], marker = "x", s=150, linewidths = 5, zorder = 10)
a = np.arange(0, len(X), 5)
ax.set_xticks(a)
ax.set_xticklabels(encoder.inverse_transform(a.astype(int)))
ax.tick_params(axis='x', colors='lightseagreen')
ax.tick_params(axis='y', colors='lightseagreen')
plt.scatter(centroids[:, 0],centroids[:, 1], marker = "x", s=100, c="black", linewidths = 5, zorder = 10)
ax.set_title('Energy consumptions Clusters (high/medium/low)', color='gold')
ax.set_xlabel('time', color='gold')
ax.set_ylabel('date(year 2011)', color='gold')
plt.show()
"Spheres" is area which surroundings plot(cluster), as this picture.
I tried to google it.
But when I type "matplotlib spheres", I could not get any result..

The sample graph in your post looks like resulting from Generalized Gaussian Mixture where each sphere is a Gaussian 2-d density.
I'll write up a sample code shortly to demonstrate how to use GMM on your dataset and do this kind of plotting.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')
import pandas as pd
# code changes here
# ===========================================
from sklearn.mixture import GMM
# ===========================================
from sklearn.preprocessing import LabelEncoder
# replace it with you file path
MY_FILE='/home/Jian/Downloads/total_watt.csv'
df = pd.read_csv(MY_FILE, parse_dates=[0], index_col=[0])
df = df.resample('1D', how='sum')
df = df.dropna()
date = df.index.tolist()
date = [x.strftime('%Y-%m-%d') for x in date]
encoder = LabelEncoder()
date_numeric = encoder.fit_transform(date)
consumption = df[df.columns[0]].values
X = np.array([date_numeric, consumption]).T
# code changes here
# ===========================================
gmm = GMM(n_components=3, random_state=0)
gmm.fit(X)
y_pred = gmm.predict(X)
# the center is given by mean
gmm.means_
# ===========================================
import matplotlib as mpl
fig, ax = plt.subplots(figsize=(10,8))
for i, color in enumerate('rgb'):
# sphere background
width, height = 2 * 1.96 * np.sqrt(np.diagonal(gmm._get_covars()[i]))
ell = mpl.patches.Ellipse(gmm.means_[i], width, height, color=color)
ell.set_alpha(0.1)
ax.add_artist(ell)
# data points
X_data = X[y_pred == i]
ax.scatter(X_data[:,0], X_data[:,1], color=color)
# center
ax.scatter(gmm.means_[i][0], gmm.means_[i][1], marker='x', s=100, c=color)
ax.set_title('Energy consumptions Clusters (high/medium/low)', color='gold')
ax.set_xlabel('time', color='gold')
ax.set_ylabel('date(year 2011)', color='gold')
a = np.arange(0, len(X), 5)
ax.set_xticks(a)
ax.set_xticklabels(encoder.inverse_transform(a.astype(int)))
ax.tick_params(axis='x', colors='lightseagreen')
ax.tick_params(axis='y', colors='lightseagreen')

Related

pyplot 3d z axis-log plot

In order to create a 3d plot using plot_surface and wireframe I wrote this (looking here around)
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import rc
from matplotlib.ticker import MultipleLocator
import matplotlib.ticker as mticker
import numpy as np
from matplotlib.ticker import FormatStrFormatter
def log_tick_formatter(val, pos=None):
return f"10$^{{{int(val)}}}$"
data=np.genfromtxt('jpdfomegal2_90.dat')
x_len= len(np.unique(data[:, 0]))
y_len= len(np.unique(data[:, 1]))
X = data[:, 0].reshape(x_len, y_len)
Y = data[:, 1].reshape(x_len, y_len)
Z = data[:, 2].reshape(x_len, y_len)
#identify lowest non-negative Z value Zmin>0
Zmin = np.where(Z > 0, Z, np.inf).min()
Zmax = Z.max()
#and substitute zero with a slightly lower value than Zmin
Z[Z==0] = 0.9 * Zmin
#log transformation because the conversion in 3D
#does not work well in matplotlib
Zlog = np.log10(Z)
rc('font',family='palatino')
rc('font',size=18)
fig = plt.figure(figsize=(12,8))
#ax = fig.add_subplot(projection='3d')
ax = Axes3D(fig)
ax.set_xlim3d(0,15)
ax.set_zlim3d(np.floor(np.log10(Zmin))-1, np.ceil(np.log10(10)))
ax.zaxis.set_major_formatter(mticker.FuncFormatter(log_tick_formatter))
ax.zaxis.set_major_locator(mticker.MaxNLocator(integer=True))
rc('font',family='palatino')
rc('font',size=18)
tmp_planes = ax.zaxis._PLANES
ax.zaxis._PLANES = ( tmp_planes[2], tmp_planes[3],
tmp_planes[0], tmp_planes[1],
tmp_planes[4], tmp_planes[5])
ax.set_xlabel('$\omega^2 /<\omega^2>$')
ax.xaxis.labelpad = 10
ax.yaxis.labelpad = 10
ax.set_ylabel('cos$(\omega,\lambda^2)$')
ax.zaxis.set_rotate_label(False) # disable automatic rotation
ax.zaxis.labelpad = 10
ax.set_zlabel('')
ax.view_init(elev=17, azim=-60)
ax.grid(False)
ax.xaxis.pane.set_edgecolor('black')
ax.yaxis.pane.set_edgecolor('black')
ax.zaxis.pane.set_edgecolor('black')
ax.xaxis.pane.fill = False
ax.yaxis.pane.fill = False
ax.zaxis.pane.fill = False
ax.xaxis.set_major_locator(MultipleLocator(2))
ax.yaxis.set_major_locator(MultipleLocator(0.2))
ax.zaxis.set_major_locator(MultipleLocator(1))
#not sure this axis scaling routine is really necessary
scale_x = 1
scale_y = 1
scale_z = 0.8
ax.get_proj = lambda: np.dot(Axes3D.get_proj(ax), np.diag([scale_x, scale_y, scale_z, 1]))
ax.contour(X, Y, np.log10(Z), 4, lw=0.1, colors="k", linestyles="--", offset=np.floor(np.log10(Zmin))-1)#-7)
surf = ax.plot_surface(X, Y, np.log10(Z), cmap="binary", lw=0.1,alpha=0.5)
ax.plot_wireframe(X, Y, np.log10(Z),linewidth=1,color='k')
ax.contour(X, Y, np.log10(Z), 4, lw=0.1, colors="k", linestyles="solid")
fig.colorbar(surf, shrink=0.5, aspect=20)
plt.tight_layout()
plt.savefig('jpdf_lambda2_90.png', bbox_inches='tight')
plt.show()
the problem is related to the "minorticks" along zaxis .. I obtain this :
but I would have this format and ticks in the axis
Does somebody clarify how to obtain it and as well I did not find a way to use the log scale in pyplot 3d
There's an open bug on log-scaling in 3D plots, and it looks like there won't be a fix any time soon.
You can use a matplotlib.ticker.FixedLocator to add the z-axis minor ticks, as shown below.
I didn't have your data, so I've plotted an arbitrary surface.
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import rc
from matplotlib.ticker import MultipleLocator, FixedLocator
import matplotlib.ticker as mticker
import numpy as np
from matplotlib.ticker import FormatStrFormatter
def log_tick_formatter(val, pos=None):
return f"10$^{{{int(val)}}}$"
x = np.linspace(1,15,15)
y = np.linspace(0,1,15)
X, Y = np.meshgrid(x, y)
Z = 1 + X**2 * Y**2
#identify lowest non-negative Z value Zmin>0
Zmin = np.where(Z > 0, Z, np.inf).min()
Zmax = Z.max()
#and substitute zero with a slightly lower value than Zmin
Z[Z==0] = 0.9 * Zmin
rc('font',family='palatino')
rc('font',size=18)
fig = plt.figure(figsize=(12,8))
ax = Axes3D(fig, auto_add_to_figure=False)
fig.add_axes(ax)
ax.set_xlim3d(0,15)
ax.set_zlim3d(np.floor(np.log10(Zmin))-1, np.ceil(np.log10(Zmax)))
ax.zaxis.set_major_formatter(mticker.FuncFormatter(log_tick_formatter))
tmp_planes = ax.zaxis._PLANES
ax.zaxis._PLANES = ( tmp_planes[2], tmp_planes[3],
tmp_planes[0], tmp_planes[1],
tmp_planes[4], tmp_planes[5])
ax.set_xlabel('$\omega^2 /<\omega^2>$')
ax.xaxis.labelpad = 10
ax.yaxis.labelpad = 10
ax.set_ylabel('cos$(\omega,\lambda^2)$')
ax.zaxis.set_rotate_label(False) # disable automatic rotation
ax.zaxis.labelpad = 10
ax.set_zlabel('')
ax.view_init(elev=17, azim=-60)
ax.grid(False)
ax.xaxis.pane.set_edgecolor('black')
ax.yaxis.pane.set_edgecolor('black')
ax.zaxis.pane.set_edgecolor('black')
ax.xaxis.pane.fill = False
ax.yaxis.pane.fill = False
ax.zaxis.pane.fill = False
ax.xaxis.set_major_locator(MultipleLocator(2))
ax.yaxis.set_major_locator(MultipleLocator(0.2))
ax.zaxis.set_major_locator(MultipleLocator(1))
# Z minor ticks
zminorticks = []
zaxmin, zaxmax = ax.get_zlim()
for zorder in np.arange(np.floor(zaxmin),
np.ceil(zaxmax)):
zminorticks.extend(np.log10(np.linspace(2,9,8)) + zorder)
ax.zaxis.set_minor_locator(FixedLocator(zminorticks))
#not sure this axis scaling routine is really necessary
scale_x = 1
scale_y = 1
scale_z = 0.8
ax.get_proj = lambda: np.dot(Axes3D.get_proj(ax), np.diag([scale_x, scale_y, scale_z, 1]))
ax.contour(X, Y, np.log10(Z), 4, colors="k", linestyles="--", offset=np.floor(np.log10(Zmin))-1)#-7)
surf = ax.plot_surface(X, Y, np.log10(Z), cmap="binary", lw=0.1,alpha=0.5)
ax.plot_wireframe(X, Y, np.log10(Z),linewidth=1,color='k')
ax.contour(X, Y, np.log10(Z), 4, colors="k", linestyles="solid")
fig.colorbar(surf, shrink=0.5, aspect=20)
# get a warning that Axes3D is incompatible with tight_layout()
# plt.tight_layout()
# for saving
# fig.savefig('log3d.png')
plt.show()

Flight Path by shapely LineString is not correct

I want to connect airplanes in origin (lat_1 lon_1) to dest(lat_2 lon_2). I use these data.
callsign
latitude_1
longitude_1
latitude_2
longitude_2
0
HBAL102
-4.82114
-76.3194
-4.5249
-79.0103
1
AUA1028
-33.9635
151.181
48.1174
16.55
2
ABW120
41.9659
-87.8832
55.9835
37.4958
3
CSN461
33.9363
-118.414
50.0357
8.5723
4
ETH3730
25.3864
55.4221
50.6342
5.43903
But unfortunately, I would get an incorrect result when creating LineString with shapely. I used everything like rotate and affine but it didn't correct.
Code:
cols = pd.read_csv("/content/dirct_lines.csv",sep=";")
line = cols[["callsign","latitude_1","longitude_1","latitude_2","longitude_2"]].dropna()
line['geometry'] = line.apply(lambda x: [(x['latitude_1'],
x['longitude_1']),
(x['latitude_2'],
x['longitude_2'])], axis = 1)
geoline = gpd.GeoDataFrame(line,geometry="geometry",
crs="EPSG:4326")
import matplotlib.pyplot as plt
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
ax = world.plot(figsize=(14,9),
color='white', edgecolor='black')
geoline.plot(figsize=(14,9),ax=ax,facecolor = 'lightgrey', linewidth = 1.75,
edgecolor = 'red',
alpha = 2)
plt.show()
Shapely Output:
something that was interesting for me was that when I use Matplotlib to create lines everything is correct.
Code:
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(projection=ccrs.PlateCarree())
ax.stock_img()
org_lon, org_lat = cols["longitude_1"], cols["latitude_1"]
dst_lon, dst_lat = cols["longitude_2"], cols["latitude_2"]
plt.plot([org_lon, dst_lon], [org_lat, dst_lat],
color='black', linewidth=0.5, marker='_',
transform=ccrs.PlateCarree()
)
plt.savefig(f"fight_path.png",dpi=60,facecolor = None, bbox_inches = 'tight', pad_inches = None)
plt.show()
Matplotlib Output:
What is the problem?
why isn't correct by shapely?
it's just the way you are creating the geometry. Below works correctly.
import io
import geopandas as gpd
import pandas as pd
import shapely.geometry
df = pd.read_csv(
io.StringIO(
"""callsign,latitude_1,longitude_1,latitude_2,longitude_2
HBAL102,-4.82114,-76.3194,-4.5249,-79.0103
AUA1028,-33.9635,151.181,48.1174,16.55
ABW120,41.9659,-87.8832,55.9835,37.4958
CSN461,33.9363,-118.414,50.0357,8.5723
ETH3730,25.3864,55.4221,50.6342,5.43903
"""
)
)
geoline = gpd.GeoDataFrame(
geometry=[
shapely.geometry.LineString(points)
for points in zip(
gpd.points_from_xy(df["longitude_1"], df["latitude_1"]),
gpd.points_from_xy(df["longitude_2"], df["latitude_2"]),
)
],
data=df,
)
import matplotlib.pyplot as plt
world = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres"))
ax = world.plot(figsize=(14, 9), color="white", edgecolor="black")
geoline.plot(
figsize=(14, 9),
ax=ax,
facecolor="lightgrey",
linewidth=1.75,
edgecolor="red",
)
plt.show()

Matplotlib clearing the figure/axis for new plot

am trying to figure out how to clear the axis in readiness for new plotting, I have tried ax.clf(), fig.clf() but nothing is happening. where am I not doing well? at the moment am not getting any errors and am using Matplotlib vers. 3.4.3.
from tkinter import *
import matplotlib.pyplot as plt
import numpy as np
import time
import datetime
import mysql.connector
import matplotlib.dates as mdates
my_connect = mysql.connector.connect(host="localhost", user="Kennedy", passwd="Kennerdol05071994", database="ecg_db", auth_plugin="mysql_native_password")
mycursor = my_connect.cursor()
voltage_container = []
time_container = []
def analyze_voltage_time():
global ax, fig
pat_id = 1
query = "SELECT voltage, time FROM ecg_data_tbl where patient_id = " +str(pat_id)
mycursor.execute(query)
result = mycursor .fetchall()
voltage, time = list(zip(*result))
for volts in voltage:
voltage_container.append(volts)
for tim in time:
time_container.append(str(tim))
fig = plt.figure(1, figsize = (15, 6), dpi = 80, constrained_layout = True)
ax = fig.add_subplot()
ax.plot(time_container, voltage_container)
for label in ax.get_xticklabels():
label.set_rotation(40)
label.set_horizontalalignment('right')
ax.set_title("Electrocadiogram")
ax.set_xlabel("Time(hh:mm:ss)")
ax.set_ylabel("Voltage(mV)")
ax.grid(b=True, which='major', color='#666666', linestyle='-')
ax.minorticks_on()
ax.grid(b=True, which='minor', color='#666666', linestyle='-', alpha=0.2)
plt.show()
def clear_():
ax.cla()
fig.clf()
# =================================MAIN GUI WINDOW======================================
analysis_window = Tk()
analysis_window.configure(background='light blue')
analysis_window.iconbitmap('lardmon_icon.ico')
analysis_window.title("ECG-LArdmon - ANALYZER")
analysis_window.geometry('400x200')
analysis_window.resizable(width=False, height=False)
# ===========================BUTTONS===================================
analyse_btn = Button(analysis_window, text='analyze', width = 20, command=analyze_voltage_time)
analyse_btn.pack()
clear_btn = Button(analysis_window, text= 'clear', width = 20, command=clear_)
clear_btn.pack()
analysis_window.mainloop()

error bars at the limits in matplotlib barchart

I'm trying to get the errorbars to show at the confidence interval's limits, and not in the center.
What I want is this:
but what I'm getting is this:
To plot the bar chart I used this:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(12345)
df = pd.DataFrame([np.random.normal(32000,200000,3650),
np.random.normal(43000,100000,3650),
np.random.normal(43500,140000,3650),
np.random.normal(48000,70000,3650)],
index=[1992,1993,1994,1995])
df1 = df.T
df1.columns = ['1992', '1993','1994','1995']
a = df1.describe()
means = a.loc['mean'].values.tolist()
stdevs = a.loc['std'].values.tolist()
counts = a.loc['count'].values.tolist()
index = np.arange(len(df1.columns))
CI = []
for i in range(len(means)):
CIval = 1.96*stdevs[i]/(counts[i]**(0.5))
CI.append(CIval)
#print(means, CI)
plt.figure()
fig, ax = plt.subplots(figsize=(10,10))
ax.set_xticks(index)
ax.set_xticklabels(df1.columns)
plt.bar(index, means, xerr = 0.1, yerr=CI)
plt.tight_layout()
plt.show()
The error bars are showing as expected. You have set a 0.1 value for the x error, however in your expected result image, there is no x errorbar so we can remove that. Secondly, we can increase the capsize of your error bars so that they are actually visible by using the capsize= in the call to plt.bar():
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(12345)
df = pd.DataFrame([np.random.normal(32000,200000,3650),
np.random.normal(43000,100000,3650),
np.random.normal(43500,140000,3650),
np.random.normal(48000,70000,3650)],
index=[1992,1993,1994,1995])
df1 = df.T
df1.columns = ['1992', '1993','1994','1995']
a = df1.describe()
means = a.loc['mean'].values.tolist()
stdevs = a.loc['std'].values.tolist()
counts = a.loc['count'].values.tolist()
index = np.arange(len(df1.columns))
CI = []
for i in range(len(means)):
CIval = 1.96*stdevs[i]/(counts[i]**(0.5))
CI.append(CIval)
fig, ax = plt.subplots(figsize=(10,10))
ax.set_xticks(index)
ax.set_xticklabels(df1.columns)
plt.bar(index, means, yerr=CI, capsize=10)
plt.tight_layout()
plt.show()

How to prevent stack plots repeating plots?

I have a code that should produce two different graphs and place them into one image and cannot figure out why it returns the last mentioned graph twice. The code is as follows:
import spacepy as sp
from spacepy import pycdf
from pylab import *
from spacepy.toolbox import windowMean, normalize
from spacepy.plot.utils import annotate_xaxis
import pylab
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import matplotlib.cbook as cbook
import matplotlib.ticker as ticker
from matplotlib.colors import LogNorm
from matplotlib.ticker import LogLocator
from matplotlib.dates import DateFormatter
from matplotlib.dates import DayLocator, HourLocator, MinuteLocator
from matplotlib import rc, rcParams
import matplotlib.dates as mdates
import datetime as dt
import bisect as bi
import seaborn as sea
import sys
import os
import multilabel as ml
import pandas as pd
sea.set_context('poster')
# sea.set_style('ticks',{'axes.facecolor':'yellow'})
sea.set_style('whitegrid')
sea.set_palette('muted',color_codes=True)
rc('text', usetex=True)
rc('font', family='Mono')
rcParams['text.latex.preamble']=[r'\usepackage{amsmath}']
MMS_1_HPCA_SURVEY_ION = pycdf.CDF(r'/home/ary/Desktop/Arya/Project/Data/MMS/1/HPCA/Survey/Ion/mms1_hpca_srvy_l2_ion_20151025120000_v1.0.0.cdf')
EPOCH_SURVEY_ION_1 = MMS_1_HPCA_SURVEY_ION['Epoch'][...]
H_Flux_SURVEY_ION_1 = MMS_1_HPCA_SURVEY_ION['mms1_hpca_hplus_flux'][...]
O_Flux_SURVEY_ION_1 = MMS_1_HPCA_SURVEY_ION['mms1_hpca_oplus_flux'][...]
Ion_Energy_SURVEY_ION_1 = MMS_1_HPCA_SURVEY_ION['mms1_hpca_ion_energy'][...]
MMS_SURVEY_ION_1_Start_time = dt.datetime(2015, 10, 25, 12, 0, 0, 908117)
MMS_SURVEY_ION_1_Finish_time = dt.datetime(2015, 10, 25, 16, 22, 24, 403623)
dt_MMS = dt.timedelta(seconds = 15)
plt.close('all')
fig_MMS, axs_MMS = plt.subplots(2,sharex=True)
cmap = plt.get_cmap(cm.jet)
cmap.set_bad('black')
sidx_MMS_1_SURVEY_ION = bi.bisect_left(EPOCH_SURVEY_ION_1,MMS_SURVEY_ION_1_Start_time)
sidx_MMS_1_SURVEY_ION = int(sidx_MMS_1_SURVEY_ION-(sidx_MMS_1_SURVEY_ION/100))
lidx_MMS_1_SURVEY_ION = bi.bisect_left(EPOCH_SURVEY_ION_1, MMS_SURVEY_ION_1_Finish_time)
lidx_MMS_1_SURVEY_ION = int(lidx_MMS_1_SURVEY_ION+((len(EPOCH_SURVEY_ION_1)-lidx_MMS_1_SURVEY_ION)/100))
if MMS_SURVEY_ION_1_Start_time.date() == MMS_SURVEY_ION_1_Finish_time.date():
stopfmt = '%H:%M'
else:
stopfmt = '%-m/%-d/%y %H:%M'
title_1 = MMS_SURVEY_ION_1_Start_time.strftime('%m/%d/%y %H:%M')+' -'+MMS_SURVEY_ION_1_Finish_time.strftime(stopfmt)
if dt_MMS.seconds !=0:
title_1 = title_1 + ' with '+str(dt_MMS.seconds)+' second time averaging'
for j, ax in enumerate(axs_MMS.T.flatten()):
flix_1 = np.array(H_Flux_SURVEY_ION_1[sidx_MMS_1_SURVEY_ION:lidx_MMS_1_SURVEY_ION,
j, :].T)
if dt_MMS==dt.timedelta(0):
fluxwin_1 = flix_1
timewin_1 = EPOCH_SURVEY_ION_1[sidx_MMS_1_SURVEY_ION:lidx_MMS_1_SURVEY_ION]
else:
fluxwin_1=[[0 for y in range(len(flix_1))] for x_1 in range(len(flix_1))]
for i, flox in enumerate(flix_1):
fluxwin_1[i], timewin_1 = windowMean(flox, EPOCH_SURVEY_ION_1[sidx_MMS_1_SURVEY_ION:lidx_MMS_1_SURVEY_ION],
winsize=dt_MMS, overlap=dt.timedelta(0))
fluxwin_1[i] = np.array(fluxwin_1[i])
for x_1 in np.where(np.diff(EPOCH_SURVEY_ION_1[sidx_MMS_1_SURVEY_ION:lidx_MMS_1_SURVEY_ION])
>dt.timedelta(hours=1))[0]+sidx_MMS_1_SURVEY_ION:
fluxwin_1[i][bi.bisect_right(timewin_1, EPOCH_SURVEY_ION_1[x_1]):bi.bisect_right(timewin_1,
EPOCH_SURVEY_ION_1[x_1+1])]=0
fluxwin_1 = np.array(fluxwin_1)
fluxwin_1[np.where(fluxwin_1<=0)] = 0
x_1 = mdates.date2num(timewin_1)
pax_1 = ax.pcolormesh(x_1, Ion_Energy_SURVEY_ION_1, fluxwin_1, shading='turkey',cmap=cmap, vmin=1,
vmax=np.nanmax(H_Flux_SURVEY_ION_1[sidx_MMS_1_SURVEY_ION:lidx_MMS_1_SURVEY_ION,:,:]),
norm=LogNorm())
sax_1 = ax.twinx()
plt.setp(sax_1.get_yticklabels(), visible=False)
sax_1.tick_params(axis='y', right='off')
ax.set_xlim(MMS_SURVEY_ION_1_Start_time, MMS_SURVEY_ION_1_Finish_time)
ax.set_yscale('log')
ax.set_yticks([10, 100, 1000,10000])
#Allows non-log formatted values to be used for ticks
ax.yaxis.set_major_formatter(plt.ScalarFormatter())
axs_MMS[0].set_ylabel('Energy (eV)')
axs_MMS[0].set_title(title_1)
for j, ax in enumerate(axs_MMS.T.flatten()):
flix_2 = np.array(O_Flux_SURVEY_ION_1[sidx_MMS_1_SURVEY_ION:lidx_MMS_1_SURVEY_ION,
j, :].T)
if dt_MMS==dt.timedelta(0):
fluxwin_2 = flix_2
timewin_2 = EPOCH_SURVEY_ION_2[sidx_MMS_1_SURVEY_ION:lidx_MMS_1_SURVEY_ION]
else:
fluxwin_2=[[0 for y in range(len(flix_2))] for x_2 in range(len(flix_2))]
for i, flox in enumerate(flix_2):
fluxwin_2[i], timewin_2 = windowMean(flox, EPOCH_SURVEY_ION_1[sidx_MMS_1_SURVEY_ION:lidx_MMS_1_SURVEY_ION],
winsize=dt_MMS, overlap=dt.timedelta(0))
fluxwin_2[i] = np.array(fluxwin_2[i])
for x_2 in np.where(np.diff(EPOCH_SURVEY_ION_1[sidx_MMS_1_SURVEY_ION:lidx_MMS_1_SURVEY_ION])
>dt.timedelta(hours=1))[0]+sidx_MMS_1_SURVEY_ION:
fluxwin_2[i][bi.bisect_right(timewin_2, EPOCH_SURVEY_ION_1[x_2]):bi.bisect_right(timewin_2,
EPOCH_SURVEY_ION_1[x_1+1])]=0
fluxwin_2 = np.array(fluxwin_2)
fluxwin_2[np.where(fluxwin_2<=0)] = 0
x_2 = mdates.date2num(timewin_2)
pax_2 = ax.pcolormesh(x_2, Ion_Energy_SURVEY_ION_1, fluxwin_2, shading='turkey',cmap=cmap, vmin=1,
vmax=np.nanmax(O_Flux_SURVEY_ION_1[sidx_MMS_1_SURVEY_ION:lidx_MMS_1_SURVEY_ION,:,:]),
norm=LogNorm())
sax_2 = ax.twinx()
plt.setp(sax_2.get_yticklabels(), visible=False)
sax_2.tick_params(axis='y', right='off')
ax.set_xlim(MMS_SURVEY_ION_1_Start_time, MMS_SURVEY_ION_1_Finish_time)
ax.set_yscale('log')
ax.set_yticks([10, 100, 1000,10000])
#Allows non-log formatted values to be used for ticks
ax.yaxis.set_major_formatter(plt.ScalarFormatter())
axs_MMS[1].set_ylabel('Energy (eV)')
cbar_ax_1 = fig_MMS.add_axes([0.93, 0.15, 0.02, 0.7])
cb_MMS_1 = fig_MMS.colorbar(pax_1, cax=cbar_ax_1)
cb_MMS_1.set_label(r'Counts sec$^{-1}$ ster$^{-1}$ cm$^{-2}$ keV$^{-1}$')
#Sets the colorbar value range
cb_MMS_1.set_clim(1, np.nanmax(H_Flux_SURVEY_ION_1[sidx_MMS_1_SURVEY_ION:lidx_MMS_1_SURVEY_ION,:,:]))
#Redraws the colorbar
cb_MMS_1.draw_all()
and the image returned looks as such:
enter image description here
Consider the following example which corresponds to your code:
import matplotlib.pyplot as plt
fig, axs = plt.subplots(2,sharex=True, figsize=(4,2.4))
for j, ax in enumerate(axs.T.flatten()):
x_1 = [[0,1,2],[0,1,2],[0,1,2]]
y_1 = [[0,0,0],[1,1,1],[2,2,2]]
z_1 = [[6,5,4],[2,3,4],[6,5,4]]
pax_1 = ax.pcolormesh(x_1, y_1, z_1)
axs[0].set_ylabel('Energy (eV)')
axs[0].set_title("Title1")
for j, ax in enumerate(axs.T.flatten()):
x_2 = [[3,4,5],[3,4,5],[3,4,5]]
y_2 = [[0,0,0],[1,1,1],[2,2,2]]
z_2 = [[2,1,2],[2,1,2],[2,1,2]]
pax_2 = ax.pcolormesh(x_2, y_2, z_2)
axs[1].set_ylabel('Energy (eV)')
plt.show()
Here you plot each plot both axes.
Instead you need to plot to the different axes:
import matplotlib.pyplot as plt
fig, axs = plt.subplots(2,sharex=True, figsize=(4,2.4))
x_1 = [[0,1,2],[0,1,2],[0,1,2]]
y_1 = [[0,0,0],[1,1,1],[2,2,2]]
z_1 = [[6,5,4],[2,3,4],[6,5,4]]
pax_1 = axs[0].pcolormesh(x_1, y_1, z_1)
axs[0].set_ylabel('Energy (eV)')
axs[0].set_title("Title1")
x_2 = [[3,4,5],[3,4,5],[3,4,5]]
y_2 = [[0,0,0],[1,1,1],[2,2,2]]
z_2 = [[2,1,2],[2,1,2],[2,1,2]]
pax_2 = axs[1].pcolormesh(x_2, y_2, z_2)
axs[1].set_ylabel('Energy (eV)')
plt.show()