I calculated the rttMeans and rttStds arrays. However, the value of rttStds makes the lower error less than 0.
rttStds = [3.330311915835426, 3.3189677330174883, 3.3319538853150386, 3.325173772304221, 3.3374145232695813]
How to set lower error to 0 instead of -#?
The python bar plot code is bellow.
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(rc={'figure.figsize':(18,16)},style='ticks',font_scale = 1.5,font='serif')
N = 5
ind = ['RSU1', 'RSU2', 'RSU3', 'RSU4', 'RSU5'] # the x locations for the groups
width = 0.4 # the width of the bars: can also be len(x) sequence
fig = plt.figure(figsize=(10,6))
ax = fig.add_subplot(111)
p1 = plt.bar(ind, rttMeans, width, yerr=rttStds, log=False, capsize = 16, color='green', hatch="/", error_kw=dict(elinewidth=3,ecolor='black'))
plt.margins(0.01, 0)
#Optional code - Make plot look nicer
plt.xticks(rotation=0)
i=0.18
for row in rttMeans:
plt.text(i, row, "{0:.1f}".format(row), color='black', ha="center")
i = i + 1
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
params = {'axes.titlesize':24,
'axes.labelsize':24,
'xtick.labelsize':28,
'ytick.labelsize':28,
'legend.fontsize': 24,
'axes.spines.right':False,
'axes.spines.top':False}
plt.rcParams.update(params)
plt.tick_params(axis="y", labelsize=28, labelrotation=20, labelcolor="black")
plt.tick_params(axis="x", labelsize=28, labelrotation=20, labelcolor="black")
plt.ylabel('RT Time (millisecond)', fontsize=24)
plt.title('# Participating RSUs', fontsize=24)
# plt.savefig('RSUs.pdf', bbox_inches='tight')
plt.show()
You can pass yerr as a pair [lower_errors, upper_errors] where you can control lower_errors :
lowers = np.minimum(rttStds,rttMeans)
p1 = plt.bar(ind, rttMeans, width, yerr=[lowers,rttStds], log=False, capsize = 16, color='green', hatch="/", error_kw=dict(elinewidth=3,ecolor='black'))
Output:
Related
I need to create a plot as close to this picture as possible (given the generated dataframe code below):
And here's the output plot of my code:
What I am having problems with is:
The edge of fill_between is not sharp as in the picture. What I have is some kind of white shadow. How do I change the line between the fillings to match a target picture?
How do I aling legend color lines to the center, but not to the left border which my code does?
Here's my code:
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cm
import numpy as np
import pandas as pd
ncols = 10
figsize = (20, 5)
fontsize = 14
dti = pd.date_range('2013-01-01', '2020-12-31', freq='2W')
probabilities_in_time = np.random.random((ncols, len(dti)))
probabilities_in_time = probabilities_in_time / \
probabilities_in_time.sum(axis=0)
probabilities_in_time = pd.DataFrame(probabilities_in_time).T
probabilities_in_time.index = dti
cm_subsection = np.linspace(0, 1, ncols)
colors = [cm.coolwarm(x) for x in cm_subsection]
def plot_time_probabilities(probabilities_in_time, figsize):
plt.figure(figsize=figsize)
plt.yticks(np.arange(0, 1.2, 0.2), fontsize=fontsize)
plt.xticks(fontsize=fontsize)
draw_stack_plot(colors, probabilities_in_time)
set_grid()
set_legend()
plt.show()
def draw_stack_plot(colors, probabilities_in_time):
for i, color in enumerate(colors):
if i == 0:
plt.plot(probabilities_in_time[i], color=color)
plt.fill_between(probabilities_in_time.index,
probabilities_in_time[0], color=color)
else:
probabilities_in_time[i] += probabilities_in_time[i-1]
plt.fill_between(probabilities_in_time.index,
probabilities_in_time[i], probabilities_in_time[i-1],
color=color)
plt.plot(probabilities_in_time[i], label=' Probability: {}'.format(
i), color=color)
def set_grid():
ax = plt.gca()
ax.set_axisbelow(False)
ax.xaxis.grid(True, linestyle='-', lw=1)
def set_legend():
leg = plt.legend(loc='lower left', fontsize=14, handlelength=1.3)
for i in leg.legendHandles:
i.set_linewidth(12)
plot_time_probabilities(probabilities_in_time, figsize)
To set the legend in the center, you can set loc='center', or you can put the legend outside. To avoid that the legend handles grow to larger, you can leave out .set_linewidth(12) (this sets a very wide edge width of 12 points).
Shifting the colors by one position can help to show the fill borders more pronounced. To still have a correct legend, the label should then be added to fill_between.
The code below also tries to simplify part of the calls:
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
import pandas as pd
ncols = 10
figsize = (20, 5)
fontsize = 14
dti = pd.date_range('2013-01-01', '2020-12-31', freq='2W')
probabilities_in_time = np.random.random((ncols, len(dti)))
probabilities_in_time = probabilities_in_time / probabilities_in_time.sum(axis=0)
probabilities_in_time = pd.DataFrame(probabilities_in_time).T
probabilities_in_time.index = dti
cm_subsection = np.linspace(0, 1, ncols)
colors = cm.coolwarm(cm_subsection)
def plot_time_probabilities(probabilities_in_time, figsize):
plt.figure(figsize=figsize)
plt.yticks(np.arange(0, 1.2, 0.2), fontsize=fontsize)
plt.xticks(fontsize=fontsize)
draw_stack_plot(colors, probabilities_in_time)
set_grid()
set_legend()
# plt.margins(x=0, y=0)
plt.margins(x=0.02)
plt.tight_layout()
plt.show()
def draw_stack_plot(colors, probabilities_in_time):
current_probabilities = 0
for i, color in enumerate(colors):
plt.fill_between(probabilities_in_time.index,
probabilities_in_time[i] + current_probabilities, current_probabilities,
color=color, label=f' Probability: {i}')
current_probabilities += probabilities_in_time[i]
plt.plot(current_probabilities,
color=colors[0] if i <= 1 else colors[-1] if i >= 8 else colors[i - 1] if i < 5 else colors[i + 1])
def set_grid():
ax = plt.gca()
ax.set_axisbelow(False)
ax.xaxis.grid(True, linestyle='-', lw=1)
def set_legend():
leg = plt.legend(loc='lower left', fontsize=14, handlelength=1.3)
# leg = plt.legend(loc='upper left', bbox_to_anchor=(1.01, 1), fontsize=14, handlelength=1.3)
# for i in leg.legendHandles:
# i.set_linewidth(12)
plot_time_probabilities(probabilities_in_time, figsize)
I need to plot a hist with bot logarithmic y and x-axis, but I'd like also to have hist's bins displayed of same size.
How can I achieve this result with the following code (the x used is very long so I have intentionally avoided to insert it):
import matplotlib as plt
import numpy as np
fig, ax1 = plt.subplots()
hist, bins, _ = ax1.hist(x, log=True, color="red", rwidth=0.5)
plt.xscale("log")
np_x = np.array(x)
print("np_x.mean() = " + str(np_x.mean()))
plt.axvline(np_x.mean() * 1.1, color='lime', linestyle='dashed', linewidth=3,
label='Mean: {:.2f}'.format(np_x.mean()))
handles, labels = ax1.get_legend_handles_labels()
binwidth = math.floor(bins[1] - bins[0])
mylabel = "Binwidth: {}".format(binwidth) + ", Bins: {}".format(len(hist))
red_patch = mpatches.Patch(color='red', label=mylabel)
handles = [red_patch] + handles
labels = [mylabel] + labels
ax1.legend(handles, labels)
plt.xlabel(x_label)
plt.ylabel(y_label)
plt.show()
I'm trying to break up my x axis in 5 parts. There exists many answers on how to break it up in 2 parts, so I've followed the same strategy but it doesn't work for more than 2 parts.
Has anyone ever succeeded breaking up an axis in more than 2 parts?
import numpy as np
from pylab import *
import matplotlib.pyplot as plt
fig,(ax,ax2,ax3,ax4,ax5) = plt.subplots(1,2,sharey=True)
ax.plot(wvln0,alb0,linestyle='-', marker='o', color='r',linewidth=1.0,label='Haze = 0T')
ax2.plot(wvln0,alb0,linestyle='-', marker='o', color='r',linewidth=1.0,label='Haze = 0T')
ax3.plot(wvln0,alb0,linestyle='-', marker='o', color='r',linewidth=1.0,label='Haze = 0T')
ax4.plot(wvln0,alb0,linestyle='-', marker='o', color='r',linewidth=1.0,label='Haze = 0T')
ax5.plot(wvln0,alb0,linestyle='-', marker='o', color='r',linewidth=1.0,label='Haze = 0T')
ax.set_xlim(0.15,1.10)
ax2.set_xlim(1.15,2.25)
ax3.set_xlim(1.20,1.30)
ax4.set_xlim(1.55,1.65)
ax5.set_xlim(1.95,2.15)
ax.spines['right'].set_visible(False)
ax2.spines['left'].set_visible(False)
ax.yaxis.tick_left()
ax.tick_params(labeltop='off') # don't put tick labels at the top
ax2.yaxis.tick_right()
plt.subplots_adjust(wspace=0.1)
axes = plt.gca()
axes.set_ylim([0.0,0.72])
plt.show()
Returns
Traceback (most recent call last):
File "/Users/jadecheclair/Documents/NASA Ames Research/NASA Codes/Wavlengths_Rages/wvln_alb.py", line 37, in <module>
fig,(ax,ax2,ax3,ax4,ax5) = plt.subplots(1,2,sharey=True)
ValueError: need more than 2 values to unpack
And if I try to change the line to
fig,(ax,ax2,ax3,ax4,ax5) = plt.subplots(1,2,3,4,5,sharey=True)
It returns
Traceback (most recent call last):
File "/Users/jadecheclair/Documents/NASA Ames Research/NASA Codes/Wavlengths_Rages/wvln_alb.py", line 37, in <module>
fig,(ax,ax2,ax3,ax4,ax5) = plt.subplots(1,2,3,4,5,sharey=True)
TypeError: subplots() got multiple values for keyword argument 'sharey'
This is a example showing how I've done it by placing three axes manually in a figure.
from __future__ import division, unicode_literals
import matplotlib.pyplot as plt
import numpy as np
plt.close('all')
# ----- PREPARE DATA ----
t = np.arange(0, 7 * 10**5, 10)
x = np.abs(np.sin(t/10.**2)) * 300
# ----- FIG CREATION ----
fig = plt.figure(figsize=(8, 5), facecolor='white')
# Margins (dimensions are in inches):
left_margin = 0.6 / fig.get_figwidth()
right_margin = 0.25 / fig.get_figwidth()
bottom_margin = 0.75 / fig.get_figheight()
top_margin = 0.25 / fig.get_figwidth()
mid_margin = 0.1 / fig.get_figwidth() # horizontal space between subplots
# ----- DEFINE PARAMETERS FOR EACH AXE ----
# Proportion of the figure's width taken by each axe (the sum must == 1):
f = [0.5, 0.3, 0.2]
xmin = [200, 50, 0] # xaxis minimum values for each axe
xmax = [8200, 200, 50] # xaxis maximum values for each axe
xscl = [2000, 50, 10] # xaxis scale for each axe
ymin, ymax = 0, 320 # yaxis minimum and maximum values
colors = ['green', 'blue', 'red'] # colors of each plot
labels = ['label1', 'label2', 'label3'] # labels of each plot for the legend
Naxes = len(f) # Total number of axes to add to the figure.
x0, y0 = left_margin, bottom_margin # origin point of the axe
h = 1 - (bottom_margin + top_margin) # height of the axe
# total width of the axes:
wtot = 1 - (left_margin + right_margin + (Naxes-1)*mid_margin)
lines = [] # to store handles for generating the legend later on
for i in range(Naxes):
# ----- AXES CREATION ----
w = wtot*f[i] # width of the current axe
ax = fig.add_axes([x0, y0, w, h], frameon=True, axisbg='none')
if i == 0: # First axe to the left
ax.spines['right'].set_visible(False)
ax.tick_params(right='off', labelright='off')
elif i == Naxes-1: # Last axe to the right
ax.spines['left'].set_visible(False)
ax.tick_params(left='off', labelleft='off',
right='off', labelright='off')
else:
ax.spines['left'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.tick_params(left='off', labelleft='off',
right='off', labelright='off')
# origin point of the next axe to be added to the figure:
x0 += w + mid_margin
# ----- SETUP XTICKS ----
if i == Naxes-1:
xticks = np.arange(xmin[i], xmax[i] + xscl[i]/2, xscl[i])
else:
xticks = np.arange(xmin[i]+xscl[i], xmax[i] + xscl[i]/2, xscl[i])
ax.set_xticks(xticks)
ax.xaxis.set_ticks_position('bottom')
ax.tick_params(axis='x', direction='out', labelsize=8)
xticks_minor = np.arange(xmin[i], xmax[i] + xscl[i]/5., xscl[i] / 5.)
ax.set_xticks(xticks_minor, minor=True)
ax.tick_params(axis='x', which='minor', direction='out')
# ----- PLOT DATA ----
line, = ax.plot(t, x, color=colors[i])
lines.append(line) # for plotting the legend
ax.axis([xmin[i], xmax[i], ymin, ymax])
ax.invert_xaxis()
# ---- SET XAXIS LABEL ----
fig.axes[0].set_xlabel('Time (years)', fontsize=12, va='bottom', ha='center')
fig.axes[0].xaxis.set_label_coords(0.5, 0.05, transform=fig.transFigure)
# ----- LEGEND ----
fig.axes[0].legend(lines, labels, loc=(0.1, 0.1), ncol=1, fancybox=True,
fontsize=12)
# ----- SHOW FIG ----
fig.savefig('SingleAxeThreeScale.png')
plt.show()
Which results in:
Problem 1
You are not calling plt.subplots correctly. Here is the default usage
subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)
Seems like you want 5 subplots in a row, so set nrows=1, and ncols=5
fig,axs = plt.subplots(nrows=1,ncols=5,sharey=True)
ax, ax2, ax3, ax4, ax5 = axs
Problem 2
You need to set the spines correctly- you only want the leftmost and rightmost to ve visible. It is easy to accomplish this with a function:
def multi_spine_adj( axs):
axs[0].spines['right'].set_visible(False)
axs[0].yaxis.tick_left()
for ax in axs[1:-1]:
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
axs[-1].spines['left'].set_visible(False)
axs[-1].yaxis.tick_right()
#wvln0 = np.linspace( 0,5,50) # make some fake data
#alb0 = np.random.random(50) #make some fake data
opts = {'linestyle':'-', 'marker':'o', 'color':'r','linewidth':1,'label':'Haze = 0T'}
fig,axs = plt.subplots(1,5,sharey=True)
xlims = [(0.15,1.10),
(1.15,2.25),
(1.20,1.30),
(1.55,1.65),
(1.95,2.15)]
for i,ax in enumerate(axs):
x1,x2 = xlims[i]
ax.plot(wvln0,alb0,**opts)
ax.set_xlim(x1,x2)
multi_spine_adj(axs)
plt.show()
Tip
Note how you can easily iterate over the axs, this makes your code cleaner and easier to modify (if you want to add more breaks for example)
I am trying to build a chart using matplotlib but unfortunately I cannot figure it out how to label the y axis. I want to do this starting from 0.1 to 1.0 with a 0.1 difference.
I managed to set its limits like this:
import numpy as np
import matplotlib.pyplot as plt
N = 10
menMeans = (0.58836, 0.6224, 0.73047, 0.79147, 0.79284, 0.79264, 0.79922, 0.82043, 0.81834, 0.74767)
ind = np.arange(N) # the x locations for the groups
width = 0.20 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(ind, menMeans, width, color='g')
womenMeans = (0.61139, 0.62270, 0.63627, 0.75868, 0.73087, 0.73128, 0.77205, 0.59866, 0.59385, 0.59891)
rects2 = ax.bar(ind+width, womenMeans, width, color='b')
# add some
ax.set_ylabel('Accuracy')
ax.set_xticks(ind+width)
ax.set_xticklabels( ('Naive', 'Norm', 'Unigrams \n(FreqDist)', 'Unigrams(LLR)', 'Unigrams (LLR)\n Bigrams', 'Unigrams (LLR)\n Bigrams (CHI)',
'Unigrams (LLR)\n Bigrams (LLR)', 'Features', 'POS', 'LDA') )
ax.legend( (rects1[0], rects2[0]), ('Naive Bayes', 'Maximum Entropy') )
ax.set_ylim(0, 1)
plt.grid(axis='y', linestyle='-')
plt.show()
but numbers on y axis show up only with a 0.2 difference. Any solution for this? Thank you!
Try this:
ax.set_ylim(0.1, 1)
import matplotlib.ticker as tick
ax.yaxis.set_major_locator(tick.MultipleLocator(0.1))
In this example the color is correlative to the radius of each bar. How would one add a colorbar to this plot?
My code mimics a "rose diagram" projection which is essentially a bar chart on a polar projection.
here is a part of it:
angle = radians(10.)
patches = radians(360.)/angle
theta = np.arange(0,radians(360.),angle)
count = [0]*patches
for i, item in enumerate(some_array_of_azimuth_directions):
temp = int((item - item%angle)/angle)
count[temp] += 1
width = angle * np.ones(patches)
# force square figure and square axes looks better for polar, IMO
fig = plt.figure(figsize=(8,8))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)
rmax = max(count) + 1
ax.set_rlim(0,rmax)
ax.set_theta_offset(np.pi/2)
ax.set_thetagrids(np.arange(0,360,10))
ax.set_theta_direction(-1)
# project strike distribution as histogram bars
bars = ax.bar(theta, count, width=width)
r_values = []
colors = []
for r,bar in zip(count, bars):
r_values.append(r/float(max(count)))
colors.append(cm.jet(r_values[-1], alpha=0.5))
bar.set_facecolor(colors[-1])
bar.set_edgecolor('grey')
bar.set_alpha(0.5)
# Add colorbar, make sure to specify tick locations to match desired ticklabels
colorlist = []
r_values.sort()
values = []
for val in r_values:
if val not in values:
values.append(val*float(max(count)))
color = cm.jet(val, alpha=0.5)
if color not in colorlist:
colorlist.append(color)
cpt = mpl.colors.ListedColormap(colorlist)
bounds = range(max(count)+1)
norm = mpl.colors.BoundaryNorm(values, cpt.N-1)
cax = fig.add_axes([0.97, 0.3, 0.03, 0.4])
cb = mpl.colorbar.ColorbarBase(cax, cmap=cpt,
norm=norm,
boundaries=bounds,
# Make the length of each extension
# the same as the length of the
# interior colors:
extendfrac='auto',
ticks=[bounds[i] for i in range(0, len(bounds), 2)],
#ticks=bounds,
spacing='uniform')
and here is the resulting plot:
As you can see, the colorbar is not quite right. If you look closely, between 16 and 17, there is a color missing (darker orange) and according to the colorbar the yellows reach a value of 15, which is not true in the rose diagram (or the data).
I have played around with the code so much and I just can't figure out how to normalize the colorbar correctly.
The easiest way is to use a PatchCollection and pass in your "z" (i.e. the values you want to color by) as the array kwarg.
As a simple example:
import itertools
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection
import numpy as np
def main():
fig = plt.figure()
ax = fig.add_subplot(111, projection='polar')
x = np.radians(np.arange(0, 360, 10))
y = np.random.random(x.size)
z = np.random.random(y.size)
cmap = plt.get_cmap('cool')
coll = colored_bar(x, y, z, ax=ax, width=np.radians(10), cmap=cmap)
fig.colorbar(coll)
ax.set_yticks([0.5, 1.0])
plt.show()
def colored_bar(left, height, z=None, width=0.8, bottom=0, ax=None, **kwargs):
if ax is None:
ax = plt.gca()
width = itertools.cycle(np.atleast_1d(width))
bottom = itertools.cycle(np.atleast_1d(bottom))
rects = []
for x, y, w, h in zip(left, bottom, width, height):
rects.append(Rectangle((x,y), w, h))
coll = PatchCollection(rects, array=z, **kwargs)
ax.add_collection(coll)
ax.autoscale()
return coll
if __name__ == '__main__':
main()
If you want a discrete color map, it's easiest to just specify the number of intervals you'd like when you call plt.get_cmap. For example, in the code above, if you replace the line cmap = plt.get_cmap('cool') with:
cmap = plt.get_cmap('cool', 5)
Then you'll get a discrete colormap with 5 intervals. (Alternately, you could pass in the ListedColormap that you created in your example.)
If you want a "full-featured" rose diagram function, you might do something like this:
import itertools
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection
import numpy as np
def main():
azi = np.random.normal(20, 30, 100)
z = np.cos(np.radians(azi + 45))
plt.figure(figsize=(5,6))
plt.subplot(111, projection='polar')
coll = rose(azi, z=z, bidirectional=True)
plt.xticks(np.radians(range(0, 360, 45)),
['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'])
plt.colorbar(coll, orientation='horizontal')
plt.xlabel('A rose diagram colored by a second variable')
plt.rgrids(range(5, 20, 5), angle=290)
plt.show()
def rose(azimuths, z=None, ax=None, bins=30, bidirectional=False,
color_by=np.mean, **kwargs):
"""Create a "rose" diagram (a.k.a. circular histogram).
Parameters:
-----------
azimuths: sequence of numbers
The observed azimuths in degrees.
z: sequence of numbers (optional)
A second, co-located variable to color the plotted rectangles by.
ax: a matplotlib Axes (optional)
The axes to plot on. Defaults to the current axes.
bins: int or sequence of numbers (optional)
The number of bins or a sequence of bin edges to use.
bidirectional: boolean (optional)
Whether or not to treat the observed azimuths as bi-directional
measurements (i.e. if True, 0 and 180 are identical).
color_by: function or string (optional)
A function to reduce the binned z values with. Alternately, if the
string "count" is passed in, the displayed bars will be colored by
their y-value (the number of azimuths measurements in that bin).
Additional keyword arguments are passed on to PatchCollection.
Returns:
--------
A matplotlib PatchCollection
"""
azimuths = np.asanyarray(azimuths)
if color_by == 'count':
z = np.ones_like(azimuths)
color_by = np.sum
if ax is None:
ax = plt.gca()
ax.set_theta_direction(-1)
ax.set_theta_offset(np.radians(90))
if bidirectional:
other = azimuths + 180
azimuths = np.concatenate([azimuths, other])
if z is not None:
z = np.concatenate([z, z])
# Convert to 0-360, in case negative or >360 azimuths are passed in.
azimuths[azimuths > 360] -= 360
azimuths[azimuths < 0] += 360
counts, edges = np.histogram(azimuths, range=[0, 360], bins=bins)
if z is not None:
idx = np.digitize(azimuths, edges)
z = np.array([color_by(z[idx == i]) for i in range(1, idx.max() + 1)])
z = np.ma.masked_invalid(z)
edges = np.radians(edges)
coll = colored_bar(edges[:-1], counts, z=z, width=np.diff(edges),
ax=ax, **kwargs)
return coll
def colored_bar(left, height, z=None, width=0.8, bottom=0, ax=None, **kwargs):
"""A bar plot colored by a scalar sequence."""
if ax is None:
ax = plt.gca()
width = itertools.cycle(np.atleast_1d(width))
bottom = itertools.cycle(np.atleast_1d(bottom))
rects = []
for x, y, h, w in zip(left, bottom, height, width):
rects.append(Rectangle((x,y), w, h))
coll = PatchCollection(rects, array=z, **kwargs)
ax.add_collection(coll)
ax.autoscale()
return coll
if __name__ == '__main__':
main()