Zooming and plotting an inset map - python

I am trying to zoom inset my map but not sure how to do that...
here is
the map
that I want to inset. I am using this code to produce the picture
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import cartopy as cart
import cartopy.crs as ccrs
import cmocean.cm as cmo
import seaborn as sns
from glob import glob
shp_dict = {}
files = glob('ne_10m_bathymetry_all/*.shp')
assert len(files) > 0
files.sort()
for f in files:
depth = f.split('_')[-1].split('.')[0]
# depth = '-' + f.split('_')[-1].split('.')[0]
# depths.append(depth)
nei = cart.io.shapereader.Reader(f)
shp_dict[depth] = nei
depths = [d for d in shp_dict.keys()][::-1]
colors = sns.mpl_palette('cmo.ice_r',n_colors=8)
cmap = sns.mpl_palette('cmo.ice',n_colors=8,as_cmap=True)
fig = plt.figure(figsize=(13,13))
ax = plt.axes(projection=ccrs.PlateCarree())
ax.set_extent((90, 119, -5, 16), crs=ccrs.PlateCarree())
#ax.set_extent((-20, 45, -52, -20), crs=ccrs.PlateCarree())
# ax.set_facecolor('grey')
# ax.add_feature(cart.feature.LAND,color='grey')
i = 0
for depth in depths[:0]:
ax.add_geometries(shp_dict[depth].geometries(),crs=ccrs.PlateCarree(),color=colors[i])
i+=1
#Add Land
ax.add_feature(cart.feature.NaturalEarthFeature(category='physical',name='land',scale='10m'),color='grey',
zorder=0)
#Add grid line
gl = ax.gridlines(draw_labels=True, alpha = 0)
gl.right_labels = False
#gl.bottom_labels = False
# Add text
plt.text(114, 0, 'Kalimantan', fontsize=12, fontweight='bold',
horizontalalignment='center', rotation = 0, color='black')
plt.text(108, 5, 'South Chine Sea', fontsize=12, fontweight='bold',
horizontalalignment='center', rotation = -40, color='black')
plt.text(102, 10, 'Gulf of Thailand', fontsize=12, fontweight='bold',
horizontalalignment='center', rotation = 0, color='black')
plt.text(94, 0, 'Indian Ocean', fontsize=12, fontweight='bold',
horizontalalignment='center', rotation = -40, color='black')
plt.text(100, 2.5, 'Malacca Strait', fontsize=12, fontweight='bold',
horizontalalignment='center', rotation = -47, color='black')
plt.text(105, 1, 'Singapore Waters', fontsize=8, fontweight='bold',
horizontalalignment='center', rotation = 0, color='black')
plt.text(94, 10, 'Andaman Sea', fontsize=12, fontweight='bold',
horizontalalignment='center', rotation = 0, color='black')
plt.text(117.67, -3.54, 'Makassar Strait', fontsize=10, fontweight='bold',
horizontalalignment='center', rotation = 70, color='black')
plt.text(102.859, -3, 'Sumatra', fontsize=12, fontweight='bold',
horizontalalignment='center', rotation = -45, color='black')
#zoom inset
# inset axes....
axins = ax.inset_axes([0, -1.1, 1, 1])
# sub region of the original image
x1, x2, y1, y2 = 98, 102, 2.5, 5.5
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
axins.set_xticklabels([])
axins.set_yticklabels([])
plt.xticks([])
plt.yticks([])
ax.indicate_inset_zoom(axins, edgecolor="red")
and the map that I want to inset inset map
using this code
fig = plt.figure(figsize=(13,13))
ax = plt.axes(projection=ccrs.PlateCarree())
ax.set_extent((98, 102, 2.5, 5.5), crs=ccrs.PlateCarree())
#ax.set_extent((-20, 45, -52, -20), crs=ccrs.PlateCarree())
i = 0
for depth in depths[:8]:
ax.add_geometries(shp_dict[depth].geometries(),crs=ccrs.PlateCarree(),color=colors[i])
i+=1
# ax.set_facecolor('grey')
# ax.add_feature(cart.feature.LAND,color='grey')
ax.add_feature(cart.feature.NaturalEarthFeature(category='physical',name='land',scale='10m'),color='grey',
zorder=0)
#Add coastline
ax.coastlines(lw=1,resolution='10m',color='black', alpha=0.7)
#Add river
ax.add_feature(cart.feature.NaturalEarthFeature(category='physical',name='rivers_lake_centerlines',
scale='10m'), linewidth=2, facecolor='none', edgecolor='lightblue')
#Add grid line
gl = ax.gridlines(draw_labels=True, alpha = 0)
gl.right_labels = False
#Add text
plt.scatter(99.862, 3.031, marker='*', color='black',s=40, zorder=10)
plt.scatter(100.75, 4.00, marker='*', color='black',s=40, zorder=10)
plt.text(99.862, 3.061, 'Baganasahan', fontsize=10, fontweight='bold',horizontalalignment='center')
plt.text(100.75, 4.02, 'Perak River', fontsize=10, fontweight='bold',horizontalalignment='center')
plt.text(99.5, 3.623, 'M a l a c c a S t r a i t', fontsize=30, fontweight='bold',horizontalalignment='center', rotation = -50, color='skyblue')
# Add custom colorbar
axi = fig.add_axes([0.92,0.35,0.025,0.3])
# axi = fig.add_axes([0.8,0.2,0.025,0.6])
norm = matplotlib.colors.Normalize(vmin=-6000,vmax=0)
cbar = matplotlib.colorbar.ColorbarBase(ax=axi,cmap=cmap,norm=norm,
boundaries=(-np.array(depths[:8]).astype(int)).tolist()[::-1],
ticks=-np.array(depths).astype(int),
spacing='proportional',
extend='neither',
label='Depth (m)'
)
so perhaps the final version looks like this final picture
Any help would be appreciate, thanks.
so perhaps the final version looks like this final picture
Any help would be appreciate, thanks.
so perhaps the final version looks like this final picture
Any help would be appreciate, thanks.

Related

How to remove a particular grid line?

please see the result graph image below.
I wish to remove only one major grid line at y-axis value of 10 (Blue horizontal line), and keep all other grid lines.
Is there a way to do that?
plt.rcParams['font.family'] = 'Arial'
fig, ax = plt.subplots(figsize=(14.78, 9.84))
plt.xlim(0, 105)
plt.ylim(0, 10)
ax.xaxis.set_minor_locator(AutoMinorLocator(2))
ax.yaxis.set_minor_locator(AutoMinorLocator(2))
ax.spines['bottom'].set_linewidth(1.5)
ax.spines['left'].set_linewidth(1.5)
ax.spines['top'].set_linewidth(0)
ax.spines['right'].set_linewidth(0)
# Grid setting
plt.grid(True, color='#0100FF', which="major", ls="-")
plt.grid(True, color='#0BC904', which="minor", ls="-")
plt.xlabel("Indicator Amplitude, %FSH", fontsize=28, labelpad=15)
plt.ylabel("Function Generator Output, V", fontsize=28, labelpad=15)
# Axis setting
plt.tick_params(which="major", labelsize=22, length=10, pad=10, width=1.5)
plt.tick_params(which="minor", length=8, width=1.5)
# Plot scatter & line
plt.plot(FSH_axis, x_value[2:], color='black', marker='^', linewidth=1.5, markersize=8, label="40 dB")
plt.plot(FSH_axis, y_value[2:], color='red', marker='o', linewidth=1.5, markersize=8, label="60 dB")
plt.plot(FSH_axis, z_value[2:], color='blue', marker='v', linewidth=1.5, markersize=8, label="80 dB")
plt.legend(loc=(1 / 16, 58 / 90), ncol=1, fontsize=20, frameon=True, framealpha=1, edgecolor="black")
plt.show()
We can catch all gridlines with get_ygridlines(), then access individual gridlines as Line2D objects to modify them:
from matplotlib import pyplot as plt
from matplotlib.ticker import AutoMinorLocator
plt.rcParams['font.family'] = 'Arial'
fig, ax = plt.subplots(figsize=(14.78, 9.84))
plt.xlim(0, 105)
plt.ylim(0, 10)
ax.xaxis.set_minor_locator(AutoMinorLocator(2))
ax.yaxis.set_minor_locator(AutoMinorLocator(2))
ax.spines['bottom'].set_linewidth(1.5)
ax.spines['left'].set_linewidth(1.5)
ax.spines['top'].set_linewidth(0)
ax.spines['right'].set_linewidth(0)
# Grid setting
plt.grid(True, color='#0100FF', which="major", ls="-")
plt.grid(True, color='#0BC904', which="minor", ls="-")
#this part is added
#set the last horizontal gridline invisible
ygridlines = ax.get_ygridlines()
gridline_of_interest = ygridlines[-1]
gridline_of_interest.set_visible(False)
plt.xlabel("Indicator Amplitude, %FSH", fontsize=28, labelpad=15)
plt.ylabel("Function Generator Output, V", fontsize=28, labelpad=15)
# Axis setting
plt.tick_params(which="major", labelsize=22, length=10, pad=10, width=1.5)
plt.tick_params(which="minor", length=8, width=1.5)
# Plot scatter & line
FSH_axis = [10, 40, 100]
plt.plot(FSH_axis, [1, 3, 2], color='black', marker='^', linewidth=1.5, markersize=8, label="40 dB")
plt.plot(FSH_axis, [2, 2, 3], color='red', marker='o', linewidth=1.5, markersize=8, label="60 dB")
plt.plot(FSH_axis, [2, 1, 1], color='blue', marker='v', linewidth=1.5, markersize=8, label="80 dB")
plt.legend(loc=(1 / 16, 58 / 90), ncol=1, fontsize=20, frameon=True, framealpha=1, edgecolor="black")
plt.show()
Sample output:
Of course, the corresponding get_xgridlines() also exists.

Errorbar in Legend - Pandas Bar Plot

Is it possible to show the error bars in the legend?
(Like i draw in red)
They do not necessarily have to be the correct length, it is enough for me if they are indicated and recognizable.
My working sample:
import pandas as pd
import matplotlib.pyplot as plt
test = pd.DataFrame(data={'one':2000,'two':300,'three':50,'four':150}, index=['MAX'])
fig, ax = plt.subplots(figsize=(5, 3), dpi=230)
ax.set_ylim(-.12,.03)
# barplot
ax = test.loc[['MAX'],['one']].plot(position=5.5,color=['xkcd:camo green'], xerr=test.loc[['MAX'],['two']].values.T, edgecolor='black',linewidth = 0.3, error_kw=dict(lw=1, capsize=2, capthick=1),ax=ax,kind='barh',width=.025)
ax = test.loc[['MAX'],['one']].plot(position=7,color=['xkcd:moss green'], xerr=test.loc[['MAX'],['three']].values.T, edgecolor='black',linewidth = 0.3, error_kw=dict(lw=1, capsize=2, capthick=1),ax=ax,kind='barh',width=.025)
ax = test.loc[['MAX'],['one']].plot(position=8.5,color=['xkcd:light olive green'],xerr=test.loc[['MAX'],['four']].values.T, edgecolor='black',linewidth = 0.3, error_kw=dict(lw=1, capsize=2, capthick=1),ax=ax,kind='barh',width=.025)
# Legende
h0, l0 = ax.get_legend_handles_labels()
l0 = [r'MAX $1$', r'MAX $2$', r'MAX $3$']
legend = plt.legend(h0, l0, borderpad=0.15,labelspacing=0.1, frameon=True, edgecolor="xkcd:black", ncol=1, loc='upper left',framealpha=1, facecolor='white')
legend.get_frame().set_linewidth(0.3)
cur_axes = plt.gca()
cur_axes.axes.get_yaxis().set_ticklabels([])
cur_axes.axes.get_yaxis().set_ticks([])
plt.show()
I tried a few ways, no one works.
With Patch in legend_elements i get no lines for the errorbars, with the errorbar() function i can draw a figure with errorbars, but it semms not to work in the legend:
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
legend_elements = [
Line2D([1,2], [5,4], color='b', lw=1, label='Line'),
Patch(facecolor='orange', edgecolor='r', label='Color Patch'),
matplotlib.pyplot.errorbar(3, 3, yerr=None, xerr=1, marker='s',mfc='xkcd:camo green', mec='black',
ms=20, mew=2, fmt='-', ecolor="black", elinewidth=2, capsize=3,
barsabove=True, lolims=False, uplims=False, xlolims=False, xuplims=False,
errorevery=2, capthick=None, label="error"),
]
test = pd.DataFrame(data={'one':2000,'two':300,'three':50,'four':150}, index=['MAX'])
fig, ax = plt.subplots(figsize=(5, 3), dpi=230)
ax.set_ylim(-.12,.03)
# barplot
ax = test.loc[['MAX'],['one']].plot(position=5.5,color=['xkcd:camo green'], xerr=test.loc[['MAX'],['two']].values.T, edgecolor='black',linewidth = 0.3, error_kw=dict(lw=1, capsize=2, capthick=1),ax=ax,kind='barh',width=.025)
ax = test.loc[['MAX'],['one']].plot(position=7,color=['xkcd:moss green'], xerr=test.loc[['MAX'],['three']].values.T, edgecolor='black',linewidth = 0.3, error_kw=dict(lw=1, capsize=2, capthick=1),ax=ax,kind='barh',width=.025)
ax = test.loc[['MAX'],['one']].plot(position=8.5,color=['xkcd:light olive green'],xerr=test.loc[['MAX'],['four']].values.T, edgecolor='black',linewidth = 0.3, error_kw=dict(lw=1, capsize=2, capthick=1),ax=ax,kind='barh',width=.025)
# Legende
h0, l0 = ax.get_legend_handles_labels()
l0 = [r'MAX $1$', r'MAX $2$', r'MAX $3$']
legend = plt.legend(h0, l0, borderpad=0.15,labelspacing=0.1, frameon=True, edgecolor="xkcd:black", ncol=1, loc='upper left',framealpha=1, facecolor='white')
legend.get_frame().set_linewidth(0.3)
ax.legend(handles=legend_elements, loc='center')
cur_axes = plt.gca()
cur_axes.axes.get_yaxis().set_ticklabels([])
cur_axes.axes.get_yaxis().set_ticks([])
#plt.show()
Implementation based on the idea of
r-beginners:
import pandas as pd
import matplotlib.pyplot as plt
test = pd.DataFrame(data={'one':2000,'two':300,'three':50,'four':150}, index=['MAX'])
fig, ax = plt.subplots(figsize=(5, 3), dpi=150)
ax.set_ylim(0, 6)
ax.set_xlim(0, 2400)
ax1 = ax.twiny()
ax1.set_xlim(0, 2400)
ax1.set_xticks([])
ax.barh(1, width=test['one'], color=['xkcd:camo green'], edgecolor='black',linewidth = 0.3, label='MAX1')
ax.barh(2, width=test['one'], color=['xkcd:moss green'], edgecolor='black',linewidth = 0.3, label='MAX2')
ax.barh(3, width=test['one'], color=['xkcd:light olive green'], edgecolor='black',linewidth = 0.3, label='MAX3')
ax1.errorbar(test['one'], 1, xerr=test['two'], color='k', ecolor='k', fmt=',', lw=1, capsize=2, capthick=1, label='MAX1')
ax1.errorbar(test['one'], 2, xerr=test['three'], color='k', ecolor='k', fmt=',', lw=1, capsize=2, capthick=1, label='MAX2')
ax1.errorbar(test['one'], 3, xerr=test['four'], color='k', ecolor='k', fmt=',', lw=1, capsize=2, capthick=1, label='MAX3')
handler, label = ax.get_legend_handles_labels()
handler1, label1 = ax1.get_legend_handles_labels()
label1 = ['' for l in label1]
ax.legend(handler, label, loc='upper left', handletextpad=1.5)
ax1.legend(handler1, label1, loc='upper left', handletextpad=1., markerfirst=False, framealpha=0.001)
plt.show()
Changes:
ax1 gets the same limit as ax
all strings from label1 are deleted
in ax1.legend() the order of handler and label is exchanged and with the handlertextpad the error bars are shifted to the right
The method I came up with was to draw 'ax.barh' and 'ax1.errorbar()' and then superimpose the legends of each on top of each other. On one side, I minimized the transparency so that the legend below is visible; the error bar looks different because I made it biaxial.
import pandas as pd
import matplotlib.pyplot as plt
test = pd.DataFrame(data={'one':2000,'two':300,'three':50,'four':150}, index=['MAX'])
fig, ax = plt.subplots(figsize=(5, 3), dpi=230)
ax.set_ylim(0, 15)
ax.set_xlim(0, 2400)
ax1 = ax.twiny()
ax.barh(5.5, width=test['one'], color=['xkcd:camo green'], edgecolor='black',linewidth = 0.3, label='MAX1')
ax.barh(7.0, width=test['one'], color=['xkcd:moss green'], edgecolor='black',linewidth = 0.3, label='MAX2')
ax.barh(8.5, width=test['one'], color=['xkcd:light olive green'], edgecolor='black',linewidth = 0.3, label='MAX3')
ax1.errorbar(test['one'], 5.5, xerr=test['two'], color='k', ecolor='k', capsize=3, fmt='|', label='MAX1')
ax1.errorbar(test['one'], 7.0, xerr=test['three'], color='k', ecolor='k', capsize=3, fmt='|', label='MAX2')
ax1.errorbar(test['one'], 8.5, xerr=test['four'], color='k', ecolor='k', capsize=3, fmt='|', label='MAX3')
handler, label = ax.get_legend_handles_labels()
handler1, label1 = ax1.get_legend_handles_labels()
ax.legend(handler, label, loc='upper left', title='mix legend')
ax1.legend(handler1, label1, loc='upper left', title='mix legend', framealpha=0.001)
plt.show()
You can add lines manually on the chart, adjusting the color, thickness and position you prefer. It is a very manual and laborious solution, but it should work.
# Draw line
import matplotlib.lines as ln
import numpy as np
# new clear axis overlay with 0-1 limits
ax2 = plt.axes([0,0,1,1], facecolor=(1,1,1,0))
x1,y1 = np.array([[0.18, 0.21], [0.831, 0.831]])
line1 = ln.Line2D(x1, y1, lw=1, color='black', alpha=1)
x2,y2 = np.array([[0.18, 0.21], [0.783, 0.783]])
line2 = ln.Line2D(x2, y2, lw=1, color='black', alpha=1)
x3,y3 = np.array([[0.18, 0.21], [0.732, 0.732]])
line3 = ln.Line2D(x3, y3, lw=1, color='black', alpha=1)
ax2.add_line(line1)
ax2.add_line(line2)
ax2.add_line(line3)
plt.show()

How to create a visualization for events along a timeline?

I'm building a visualization with Python.
There I'd like to visualize fuel stops and the fuel costs of my car. Furthermore, car washes and their costs should be visualized as well as repairs. The fuel costs and laundry costs should have a higher bar depending on the costs. I created the visualization below to describe the concepts.
How to create such a visualization with matplotlib?
This is the visualization being built:
Yes, this kind of visualization is perfectly possible with matplotlib. To store the data, numpy arrays are usually very handy.
Here is some code to get you started:
import matplotlib.pyplot as plt
import numpy as np
refuel_km = np.array([0, 505.4, 1070, 1690])
refuel_cost = np.array([40.1, 50, 63, 55])
carwash_km = np.array([302.0, 605.4, 901, 1331, 1788.2])
carwash_cost = np.array([35.0, 40.0, 35.0, 35.0, 35.0])
repair_km = np.array([788.0, 1605.4])
repair_cost = np.array([135.0, 74.5])
fig, ax = plt.subplots(figsize=(12,3))
plt.scatter(refuel_km, np.full_like(refuel_km, 0), marker='o', s=100, color='lime', edgecolors='black', zorder=3, label='refuel')
plt.bar(refuel_km, refuel_cost, bottom=15, color='lime', ec='black', width=20, label='refuel cost')
plt.scatter(carwash_km, np.full_like(carwash_km, 0), marker='d', s=100, color='tomato', edgecolors='black', zorder=3, label='car wash')
plt.bar(carwash_km, -carwash_cost, bottom=-15, color='tomato', ec='black', width=20, label='car wash cost')
plt.scatter(repair_km, np.full_like(repair_km, 0), marker='^', s=100, color='lightblue', edgecolors='black', zorder=3, label='car repair')
#plt.bar(repair_km, -repair_cost, bottom=-15, color='lightblue', ec='black', width=20)
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_color('none')
ax.tick_params(axis='x', length=20)
ax.set_yticks([]) # turn off the yticks
_, xmax = ax.get_xlim()
ymin, ymax = ax.get_ylim()
ax.set_xlim(-15, xmax)
ax.set_ylim(ymin, ymax+25) # make room for the legend
ax.text(xmax, -5, "km", ha='right', va='top', size=14)
plt.legend(ncol=5, loc='upper left')
plt.tight_layout()
plt.show()

Error while plotting circles using matplotlib

I want to draw a (semi-transparent) circle on top of an array of randomly generated points (between [0,1] ) using python. I want the circle to be centered at (0.5, 0.5)
This is the code that I have written:
import numpy as np
import matplotlib.pyplot as plt
x_gal = np.random.rand(20)
y_gal = np.random.rand(20)
x_rand = np.random.rand(5*20)
y_rand = np.random.rand(5*20)
plt.figure(1)
plt.plot( x_gal, y_gal, ls=' ', marker='o', markersize=5, color='r' )
plt.plot( 0.5, 0.5, ls=' ', marker='o', markersize=5, color='r' )
plt.plot( x_rand, y_rand, ls=' ', marker='o', markersize=5, color='b' )
plt.axis('off')
circle1 = plt.Circle((0.5, 0.5), 0.2, color='r', alpha=0.5)
plt.add_artist(circle1)
plt.tight_layout()
plt.show()
Without the lines in the code which refer to circle1, I get normal output (without the desired circle). But when I include the lines in the code which refer to circle1, I get the following error output.
AttributeError: 'module' object has no attribute 'add_artist'
What am I missing here? Any help will be greatly appreciated.
You need to use add_artist from axes, the following is the quickest way to get the current axes using plt.gcf, get current figure, and get_gca, get current axes, also I recommend plt.axis('equal') to draw a circle vs oval:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
x_gal = np.random.rand(20)
y_gal = np.random.rand(20)
x_rand = np.random.rand(5*20)
y_rand = np.random.rand(5*20)
plt.figure(1)
plt.plot( x_gal, y_gal, ls=' ', marker='o', markersize=5, color='r' )
plt.plot( 0.5, 0.5, ls=' ', marker='o', markersize=5, color='r' )
plt.plot( x_rand, y_rand, ls=' ', marker='o', markersize=5, color='b' )
plt.axis('off')
plt.axis('equal')
circle1 = plt.Circle((0.5, 0.5), 0.2, color='r', alpha=0.5)
plt.gcf().gca().add_artist(circle1)
plt.tight_layout()
plt.show()
You need to plot on axis.
import numpy as np
import matplotlib.pyplot as plt
x_gal = np.random.rand(20)
y_gal = np.random.rand(20)
x_rand = np.random.rand(5*20)
y_rand = np.random.rand(5*20)
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot( x_gal, y_gal, ls=' ', marker='o', markersize=5, color='r' )
ax.plot( 0.5, 0.5, ls=' ', marker='o', markersize=5, color='r' )
ax.plot( x_rand, y_rand, ls=' ', marker='o', markersize=5, color='b' )
ax.axis('off')
circle1 = plt.Circle((0.5, 0.5), 0.2, color='r', alpha=0.5)
ax.add_artist(circle1)
plt.tight_layout()
plt.show()
Output:

Average line for bar chart in matplotlib

How do we draw an average line (horizontal) for a histogram in using matplotlib?
Right now, I'm able to draw the histogram without any issues.
Here is the code I'm using:
## necessary variables
ind = np.arange(N) # the x locations for the groups
width = 0.2 # the width of the bars
plt.tick_params(axis='both', which='major', labelsize=30)
plt.tick_params(axis='both', which='minor', labelsize=30)
ax2 = ax.twinx()
## the bars
rects1 = ax.bar(ind, PAAE1, width,
color='0.2',
error_kw=dict(elinewidth=2,ecolor='red'),
label='PAAE1')
rects2 = ax.bar(ind+width, PAAE2, width,
color='0.3',
error_kw=dict(elinewidth=2,ecolor='black'),
label='PAAE2')
rects3 = ax2.bar(ind+width+width, AAE1, width,
color='0.4',
error_kw=dict(elinewidth=2,ecolor='red'),
label='AAE1')
rects4 = ax2.bar(ind+3*width, AAE2, width,
color='0.5',
error_kw=dict(elinewidth=2,ecolor='black'),
label='AAE3')
maxi = max(dataset[2])
maxi1 = max(dataset[4])
f_max = max(maxi, maxi1)
lns = [rects1,rects2,rects3,rects4]
labs = [l.get_label() for l in lns]
ax.legend(lns, labs, loc='upper center', ncol=4)
# axes and labels
ax.set_xlim(-width,len(ind)+width)
ax.set_ylim(0, 100)
ax.set_ylabel('PAAE', fontsize=25)
ax2.set_ylim(0, f_max+500)
ax2.set_ylabel('AAE (mW)', fontsize=25)
xTickMarks = dataset[0]
ax.set_xticks(ind+width)
xtickNames = ax.set_xticklabels(xTickMarks)
plt.setp(xtickNames, rotation=90, fontsize=25)
I want to plot the average line for PAAE 1, 2 and AAE 1, 2.
What should I be using to plot the average line?
If you'd like a vertical line to denote the mean use axvline(x_value). This will place a vertical line that always spans the full (or specified fraction of) y-axis. There's also axhline for horizontal lines.
In other works, you might have something like this:
ax.axvline(data1.mean(), color='blue', linewidth=2)
ax.axvline(data2.mean(), color='green', linewidth=2)
As a more complete, but unnecessarily complex example (most of this is nicely annotating the means with curved arrows):
import numpy as np
import matplotlib.pyplot as plt
data1 = np.random.normal(0, 1, 1000)
data2 = np.random.normal(-2, 1.5, 1000)
fig, ax = plt.subplots()
bins = np.linspace(-10, 5, 50)
ax.hist(data1, bins=bins, color='blue', label='Dataset 1',
alpha=0.5, histtype='stepfilled')
ax.hist(data2, bins=bins, color='green', label='Dataset 2',
alpha=0.5, histtype='stepfilled')
ax.axvline(data1.mean(), color='blue', linewidth=2)
ax.axvline(data2.mean(), color='green', linewidth=2)
# Add arrows annotating the means:
for dat, xoff in zip([data1, data2], [15, -15]):
x0 = dat.mean()
align = 'left' if xoff > 0 else 'right'
ax.annotate('Mean: {:0.2f}'.format(x0), xy=(x0, 1), xytext=(xoff, 15),
xycoords=('data', 'axes fraction'), textcoords='offset points',
horizontalalignment=align, verticalalignment='center',
arrowprops=dict(arrowstyle='-|>', fc='black', shrinkA=0, shrinkB=0,
connectionstyle='angle,angleA=0,angleB=90,rad=10'),
)
ax.legend(loc='upper left')
ax.margins(0.05)
plt.show()

Categories