Issue with plots in Spyder - python

When I use plt.plot(x,y) I get the following in Spyders plot display by default:
However, I want:
black axes lines and white background. How do I set this?
ax4.axes.get_xaxis().set_visible(True)
ax4.spines['bottom'].set_color('black')
ax4.tick_params(axis='x', colors='black')
ax4.tick_params(axis='y', colors='black')
did not work.
Code to get default:
fig = plt.figure(figsize=(8.5,11))
ax4 = fig.add_subplot(3,1,2)
Dist25 = np.load('Dist25.npy')
Dist100 = np.load('Dist100.npy')
r =1
#
ax4.plot(Dist25[0::r,3],Dist25[0::r,0],'or', color = 'xkcd:azure')
ax4.plot(Dist100[0::r,3],Dist100[0::r,0],'<r', color = 'xkcd:chartreuse')
ax4.set_xscale('log')
ax4.set_ylim((1.5,2.5))
ax4.fill_between(Dist25[0::r,3], Dist25[0::r,0] - Dist25[0::r,1], Dist25[0::r,0] + Dist25[0::r,1],
color='xkcd:azure', alpha=0.2)
ax4.fill_between(Dist100[0::r,3], Dist100[0::r,0] - Dist100[0::r,1], Dist100[0::r,0] + Dist100[0::r,1],
color='xkcd:chartreuse', alpha=0.2)
for tick in ax4.xaxis.get_majorticklabels(): # example for xaxis
tick.set_fontsize(18)
for tick in ax4.yaxis.get_majorticklabels(): # example for xaxis
tick.set_fontsize(18)
ax4.set_title('B) Distance from chain', fontsize = 25)
ax4.set_xlabel('Simulation time (ps)', fontsize = 20)
ax4.set_ylabel('Distance (nm)', fontsize = 20)

I solved this by adding:
plt.style.use('classic')
to my code :)

Related

Draw multiple set of barplot + lineplot using seaborn

I'm trying to draw multiple sets of barplot + lineplot from a dataframe using seaborn like the one below (I've already succeeded in drawing one):
Here you can find the dataframe used to produce it => dataframe
What I'd like to achieve is this kind of graph (which I have already succeeded in creating) but repeated for all the possibile product families inside a speicifc product basket ('family' is a drill down level of 'product basket')
Thanks a lot for anyone who will help me. I've tried some looping but probably I'm just doing it wrong.
Here is the code that I've used to draw the above graph:
#select a family
df_perc2=df_perc.query('family=="WORKWEAR & PROTECTIVE CLOTHING"')
#set common axis
fig, ax = plt.subplots()
ax_twin = ax.twinx()
#set boxplot general aspect
fig = plt.gcf()
fig.set_size_inches(30, 10)
sns.set_style("white")
#ship_to_count bars
barplot = sns.barplot(data=df_perc2,
x = 'orders_count',
hue = 'SF_type',
y = 'ship_to_perc',
palette = "Set2",
ax = ax)
#cumulative % line
lineplot = sns.pointplot(data = df_perc2,
x = 'orders_count',
hue = 'SF_type',
y = 'running_perc',
palette = "Set2",
marker ='o',
ax = ax_twin,
legend = False)
#set tick stiles for x and y axis
barplot.set_xticklabels(barplot.get_xmajorticklabels(), fontsize = 18)
barplot.set_yticklabels(barplot.get_yticks().round(2), size = 18)
lineplot.set_yticklabels(lineplot.get_yticks().round(2), size = 18)
#set dynamic title
barplot.set_title('% Ship Tos by # orders for '+''.join(df_perc2['product_basket'].unique())
+
' - '
+
''.join(df_perc2['family'].unique()), fontdict = { 'fontsize': 30}, y = 1.05)
barplot.get_legend().remove()
#set constant line at 90%
plt.axhline(y=0.9, color='g', ls=':', lw=4, label='90th percentile')
lineplot.legend(loc='center right',fontsize='22')

Annotating subplots in matplotlib scales the figure to the largest axes

When I make figure with 5 subplots and annotate the bars in each subplot, matplotlib appears to scale the figure so that the maximum from the largest y-axis scales to the smallest y-axis.
I can't describe the problem too well, but see this image:
where there's tons of white-space above where the figure should begin.
However, the figure would ideally look like this
When I set the 4 smallest axes to have the same upper y-limit as the largest axis, then the figure scales correctly, but for the purpose of the visualization, I would prefer not to do that.
Why does this happen? Is there anyway to control the figure so that it's not automatically scaled as in the first image? Or otherwise, a more appropriate way of plotting what I hope to achieve?
The code I'm using to generate the figure:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.patches import Patch
from matplotlib import rcParams
rcParams['font.family'] = 'sans-serif'
rcParams['font.sans-serif'] = ['Arial']
department = ["100", "1,000", "10,000", \
"100,000", "1,000,000"]
quarter = ["Serial", "MPI", "CUDA", "Hybrid"]
budgets = np.array([[0.049979, 0.43584, 2.787366, 19.75062, 201.6935],\
[2.184624, 0.175213, 0.677837, 5.265575, 46.33678],\
[0.050294, 0.068537, 0.23739, 1.93778, 18.55734],\
[3.714284, 3.9917, 4.977599, 6.174967, 37.732232]])
budgets = np.transpose(budgets)
em = np.zeros((len(department), len(quarter)))
# set up barchart
x = np.arange(len(department)) # label locations
width = 0.8 # width of all the bars
# set up figure
fig, (ax1, ax2, ax3, ax4, ax5) = plt.subplots(1, 5)
axes = [ax1, ax2, ax3, ax4, ax5]
# generate bars
rects = []
color = ["tomato", "royalblue", "limegreen", "orange"]
n = len(quarter)
for i in range(n):
bar_x = x - width/2.0 + i/float(n)*width + width/(n*2)
m = len(budgets[:,i])
for j in range(m):
bar_x = x[j] - width/2.0 + i/float(n)*width + width/(n*2)
e = budgets[j,i]
#bar_x = x - width/2.0 + i/float(n)*width + width/(n*2)
rects.append(axes[j].bar(bar_x, e, width=width/float(n), \
label=quarter[i], color=color[i]))
# set figure properties
fig.set_size_inches(12, 2.5)
fig.tight_layout(rect=[0, 0.03, 1, 0.95])
nAx = len(axes)
for i in range(nAx):
#axes[i].set_aspect("auto")
axes[i].tick_params(axis='x', which='both', bottom=False, top=False,
labelbottom=False)
ax1.set_ylabel("Time (ms)")
for i in range(nAx):
axes[i].yaxis.grid(which="major", color="white", lw=0.75)
ax1.set_ylim([0, 4])
fig.suptitle("Time per iteration for differing dataset sizes") # title
for i in range(nAx):
axes[i].set_xlabel(department[i])
# annotate bars
for i in range(nAx):
for rect in rects:
j = 0;
for bar in rect:
y_bottom, y_top = axes[i].get_ylim() # axis limits
height = bar.get_height() # bar's height
va = 'bottom'
offset = 3
color = 'k'
fg = 'w'
# keep label within plot
if (y_top < 1.1 * height):
offset = -3
va = 'top'
color='w'
fg = 'k'
# annotate the bar
axes[i].annotate('{:.2f}'.format(height),
xy=(bar.get_x() + bar.get_width()/2, height),
xytext=(0,offset),
textcoords="offset points",
ha='center', va=va, color=color)
# set custom legend
legend_elements = [Patch(facecolor='tomato', label='Serial'),
Patch(facecolor='royalblue', label='MPI'),
Patch(facecolor='limegreen', label='CUDA'),
Patch(facecolor='orange', label='Hybrid')]
plt.legend(handles=legend_elements, loc="upper center", fancybox=False,
edgecolor='k', ncol=4, bbox_to_anchor=(-2, -0.1))
plt.show()
This is a partial answer.
This might be a bug, since I couldn't reproduce the problem until I switched to a Jupyter notebook in a Debian system (different hardware too). Your figure gets drawn correctly in my macOS Jupyter notebook, and in Debian when displayed from a .py script.
The problem appears to be with your annotations. If you make the tight_layout call after annotation, you might get a warning like this:
<ipython-input-80-f9f592f5efc5>:88: UserWarning: Tight layout not applied. The bottom and top margins cannot be made large enough to accommodate all axes decorations.
fig.tight_layout(rect=[0, 0.03, 1, 0.95])
It seems like the annotate function is calculating some totally wacky coordinates for your annotations, though the text ends up in the right spot. If you remove them, the white space disappears. You can try calculating the xy coordinates a for your annotations a different way. This might get you started:
axes[i].annotate('{:.2f}'.format(height),
xy=(bar.get_x() + bar.get_width()/2, height),
xytext=(0,offset),
textcoords="offset points",
xycoords="axes points", # change
ha='center', va=va, color=color)
Output:
To correctly calculate the points, you can try using the appropriate axis transformation, though again, I couldn't get it to work and it might be related to a bug.
try putting the fig.tight_layout(rect=[0, 0.03, 1, 0.95]) after all the plotting commands, as below.
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.patches import Patch
from matplotlib import rcParams
rcParams['font.family'] = 'sans-serif'
rcParams['font.sans-serif'] = ['Arial']
department = ["100", "1,000", "10,000", \
"100,000", "1,000,000"]
quarter = ["Serial", "MPI", "CUDA", "Hybrid"]
budgets = np.array([[0.049979, 0.43584, 2.787366, 19.75062, 201.6935],\
[2.184624, 0.175213, 0.677837, 5.265575, 46.33678],\
[0.050294, 0.068537, 0.23739, 1.93778, 18.55734],\
[3.714284, 3.9917, 4.977599, 6.174967, 37.732232]])
budgets = np.transpose(budgets)
em = np.zeros((len(department), len(quarter)))
# set up barchart
x = np.arange(len(department)) # label locations
width = 0.8 # width of all the bars
# set up figure
fig, (ax1, ax2, ax3, ax4, ax5) = plt.subplots(1, 5)
axes = [ax1, ax2, ax3, ax4, ax5]
# generate bars
rects = []
color = ["tomato", "royalblue", "limegreen", "orange"]
n = len(quarter)
for i in range(n):
bar_x = x - width/2.0 + i/float(n)*width + width/(n*2)
m = len(budgets[:,i])
for j in range(m):
bar_x = x[j] - width/2.0 + i/float(n)*width + width/(n*2)
e = budgets[j,i]
#bar_x = x - width/2.0 + i/float(n)*width + width/(n*2)
rects.append(axes[j].bar(bar_x, e, width=width/float(n), \
label=quarter[i], color=color[i]))
# set figure properties
fig.set_size_inches(12, 2.5)
#fig.tight_layout(rect=[0, 0.03, 1, 0.95])
nAx = len(axes)
for i in range(nAx):
#axes[i].set_aspect("auto")
axes[i].tick_params(axis='x', which='both', bottom=False, top=False,
labelbottom=False)
ax1.set_ylabel("Time (ms)")
for i in range(nAx):
axes[i].yaxis.grid(which="major", color="white", lw=0.75)
ax1.set_ylim([0, 4])
fig.suptitle("Time per iteration for differing dataset sizes") # title
for i in range(nAx):
axes[i].set_xlabel(department[i])
# annotate bars
for i in range(nAx):
for rect in rects:
j = 0;
for bar in rect:
y_bottom, y_top = axes[i].get_ylim() # axis limits
height = bar.get_height() # bar's height
va = 'bottom'
offset = 3
color = 'k'
fg = 'w'
# keep label within plot
if (y_top < 1.1 * height):
offset = -3
va = 'top'
color='w'
fg = 'k'
# annotate the bar
axes[i].annotate('{:.2f}'.format(height),
xy=(bar.get_x() + bar.get_width()/2, height),
xytext=(0,offset),
textcoords="offset points",
ha='center', va=va, color=color)
# set custom legend
legend_elements = [Patch(facecolor='tomato', label='Serial'),
Patch(facecolor='royalblue', label='MPI'),
Patch(facecolor='limegreen', label='CUDA'),
Patch(facecolor='orange', label='Hybrid')]
plt.legend(handles=legend_elements, loc="upper center", fancybox=False,
edgecolor='k', ncol=4, bbox_to_anchor=(-2, -0.1))
fig.tight_layout(rect=[0, 0.03, 1, 0.95])
plt.show()

Move x-axis tick labels one position to left [duplicate]

This question already has answers here:
Aligning rotated xticklabels with their respective xticks
(5 answers)
Closed 4 months ago.
I am making a bar chart and I want to move the x-axis tick labels one position to left. Here is the code of the plot:
matplotlib.rcParams.update(matplotlib.rcParamsDefault)
plt.style.use(['seaborn-white', 'bmh'])
fig1, ax = plt.subplots()
palette = ['#2a5495', '#07a64c', '#e979ad', '#d88432', '#2a5495',
'#b7040e', '#82c5db', '#b9c09b', '#cd065d', '#4b117f']
x = np.array(df.index)
y = np.array(df.loc[:, 2015])
width = 1.0
lefts = [x * width for x, _ in enumerate(y)]
ax.bar(left = lefts, height = y, width = width, tick_label = x, color = palette, label = ranked_univs)
ax.axis(ymin = 0, ymax = 200, xmin = -0.5, xmax = 9.5)
ax.tick_params(axis='x', which='major', labelsize=8)
ax.set_xticklabels(ax.xaxis.get_majorticklabels(), rotation=45)
fig1.tight_layout()
plt.show()
And here is the bar chart:
Any clue?
Your labels are correctly positioned, as shown by the fact that if you were to rotate them 90°, they would be perfectly aligned with your bars.
fig1, ax = plt.subplots()
palette = ['#2a5495', '#07a64c', '#e979ad', '#d88432', '#2a5495',
'#b7040e', '#82c5db', '#b9c09b', '#cd065d', '#4b117f']
labels = ['Long misaligned label {}'.format(i) for i in range(10)]
x = range(10)
y = 100+100*np.random.random((10,))
width = 1.0
lefts = [x * width for x, _ in enumerate(y)]
ax.bar(left = lefts, height = y, width = width, tick_label = labels, color = palette)
ax.axis(ymin = 0, ymax = 200, xmin = -0.5, xmax = 9.5)
ax.tick_params(axis='x', which='major', labelsize=8)
ax.set_xticklabels(ax.xaxis.get_majorticklabels(), rotation=90)
fig1.tight_layout()
plt.show()
The problem is that the labels are centered horizontally, so when you rotate them 45°, they appear to be aligned with the wrong bar. To fix this, align the labels to the right, and they'll get back to their correct (visual) position.
plt.setp(ax.xaxis.get_majorticklabels(), ha='right')
Another (maybe simpler) option is to use the helper function Figure.autofmt_xdate(), which handles all of this for you.
See this question: How can I rotate xticklabels in matplotlib so that the spacing between each xticklabel is equal?
There the solution is to align the labels to their right side:
ax.set_xticklabels(xticklabels, rotation = 45, ha="right")

How can I edit the xticks on a python twinx?

I've got two pandas series I would like to plot on the same axis, using a twinx. Here is a picture of what it looks like:
fig,(ax1,ax2,ax3,ax4,ax5) = plt.subplots(nrows = 5,ncols = 1, figsize = (8,13))
plt.subplots_adjust(hspace = 0.5)
ax1_1 = ax1.twinx()
df[["Var"]].plot(ax = ax1, label = 'Variance')
df[['w2']].plot(ax = ax1_1, color = 'g', label = '$w$')
ax1.locator_params('y',nbins = 5)
ax1_1.locator_params('y', nbins = 5)
ax1.set_ylabel('AC', labelpad = 10)
ax1_1.set_ylabel('w', labelpad = 10)
ax1.legend(loc = 'upper left')
ax1_1.legend()
I'd like to edit the x axis ticks, but using ax1.set_xticks() and ax1.set_xticklabels() doesn't seem to work. Furthermore, why are there are no x ticks after I execute the code found above? Shouldn't the ticks be the index of the Series?

How to display the value of the bar on each bar with pyplot.barh()

I generated a bar plot, how can I display the value of the bar on each bar?
Current plot:
What I am trying to get:
My code:
import os
import numpy as np
import matplotlib.pyplot as plt
x = [u'INFO', u'CUISINE', u'TYPE_OF_PLACE', u'DRINK', u'PLACE', u'MEAL_TIME', u'DISH', u'NEIGHBOURHOOD']
y = [160, 167, 137, 18, 120, 36, 155, 130]
fig, ax = plt.subplots()
width = 0.75 # the width of the bars
ind = np.arange(len(y)) # the x locations for the groups
ax.barh(ind, y, width, color="blue")
ax.set_yticks(ind+width/2)
ax.set_yticklabels(x, minor=False)
plt.title('title')
plt.xlabel('x')
plt.ylabel('y')
#plt.show()
plt.savefig(os.path.join('test.png'), dpi=300, format='png', bbox_inches='tight') # use format='svg' or 'pdf' for vectorial pictures
Update: there's a built in method for this now! Scroll down a couple answers to "New in matplotlib 3.4.0".
If you can't upgrade that far, it doesn't take much code. Add:
for i, v in enumerate(y):
ax.text(v + 3, i + .25, str(v), color='blue', fontweight='bold')
result:
The y-values v are both the x-location and the string values for ax.text, and conveniently the barplot has a metric of 1 for each bar, so the enumeration i is the y-location.
New in matplotlib 3.4.0
There is now a built-in Axes.bar_label helper method to auto-label bars:
fig, ax = plt.subplots()
bars = ax.barh(indexes, values)
ax.bar_label(bars)
Note that for grouped/stacked bar plots, there will multiple bar containers, which can all be accessed via ax.containers:
for bars in ax.containers:
ax.bar_label(bars)
More details:
How to add thousands separators (commas) to labels
How to apply f-strings to labels
How to add spacing to labels
I have noticed api example code contains an example of barchart with the value of the bar displayed on each bar:
"""
========
Barchart
========
A bar plot with errorbars and height labels on individual bars
"""
import numpy as np
import matplotlib.pyplot as plt
N = 5
men_means = (20, 35, 30, 35, 27)
men_std = (2, 3, 4, 1, 2)
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(ind, men_means, width, color='r', yerr=men_std)
women_means = (25, 32, 34, 20, 25)
women_std = (3, 5, 2, 3, 3)
rects2 = ax.bar(ind + width, women_means, width, color='y', yerr=women_std)
# add some text for labels, title and axes ticks
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind + width / 2)
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
ax.legend((rects1[0], rects2[0]), ('Men', 'Women'))
def autolabel(rects):
"""
Attach a text label above each bar displaying its height
"""
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
'%d' % int(height),
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
plt.show()
output:
FYI What is the unit of height variable in "barh" of matplotlib? (as of now, there is no easy way to set a fixed height for each bar)
Use plt.text() to put text in the plot.
Example:
import matplotlib.pyplot as plt
N = 5
menMeans = (20, 35, 30, 35, 27)
ind = np.arange(N)
#Creating a figure with some fig size
fig, ax = plt.subplots(figsize = (10,5))
ax.bar(ind,menMeans,width=0.4)
#Now the trick is here.
#plt.text() , you need to give (x,y) location , where you want to put the numbers,
#So here index will give you x pos and data+1 will provide a little gap in y axis.
for index,data in enumerate(menMeans):
plt.text(x=index , y =data+1 , s=f"{data}" , fontdict=dict(fontsize=20))
plt.tight_layout()
plt.show()
This will show the figure as:
For anyone wanting to have their label at the base of their bars just divide v by the value of the label like this:
for i, v in enumerate(labels):
axes.text(i-.25,
v/labels[i]+100,
labels[i],
fontsize=18,
color=label_color_list[i])
(note: I added 100 so it wasn't absolutely at the bottom)
To get a result like this:
I know it's an old thread, but I landed here several times via Google and think no given answer is really satisfying yet. Try using one of the following functions:
EDIT: As I'm getting some likes on this old thread, I wanna share an updated solution as well (basically putting my two previous functions together and automatically deciding whether it's a bar or hbar plot):
def label_bars(ax, bars, text_format, **kwargs):
"""
Attaches a label on every bar of a regular or horizontal bar chart
"""
ys = [bar.get_y() for bar in bars]
y_is_constant = all(y == ys[0] for y in ys) # -> regular bar chart, since all all bars start on the same y level (0)
if y_is_constant:
_label_bar(ax, bars, text_format, **kwargs)
else:
_label_barh(ax, bars, text_format, **kwargs)
def _label_bar(ax, bars, text_format, **kwargs):
"""
Attach a text label to each bar displaying its y value
"""
max_y_value = ax.get_ylim()[1]
inside_distance = max_y_value * 0.05
outside_distance = max_y_value * 0.01
for bar in bars:
text = text_format.format(bar.get_height())
text_x = bar.get_x() + bar.get_width() / 2
is_inside = bar.get_height() >= max_y_value * 0.15
if is_inside:
color = "white"
text_y = bar.get_height() - inside_distance
else:
color = "black"
text_y = bar.get_height() + outside_distance
ax.text(text_x, text_y, text, ha='center', va='bottom', color=color, **kwargs)
def _label_barh(ax, bars, text_format, **kwargs):
"""
Attach a text label to each bar displaying its y value
Note: label always outside. otherwise it's too hard to control as numbers can be very long
"""
max_x_value = ax.get_xlim()[1]
distance = max_x_value * 0.0025
for bar in bars:
text = text_format.format(bar.get_width())
text_x = bar.get_width() + distance
text_y = bar.get_y() + bar.get_height() / 2
ax.text(text_x, text_y, text, va='center', **kwargs)
Now you can use them for regular bar plots:
fig, ax = plt.subplots((5, 5))
bars = ax.bar(x_pos, values, width=0.5, align="center")
value_format = "{:.1%}" # displaying values as percentage with one fractional digit
label_bars(ax, bars, value_format)
or for horizontal bar plots:
fig, ax = plt.subplots((5, 5))
horizontal_bars = ax.barh(y_pos, values, width=0.5, align="center")
value_format = "{:.1%}" # displaying values as percentage with one fractional digit
label_bars(ax, horizontal_bars, value_format)
For pandas people :
ax = s.plot(kind='barh') # s is a Series (float) in [0,1]
[ax.text(v, i, '{:.2f}%'.format(100*v)) for i, v in enumerate(s)];
That's it.
Alternatively, for those who prefer apply over looping with enumerate:
it = iter(range(len(s)))
s.apply(lambda x: ax.text(x, next(it),'{:.2f}%'.format(100*x)));
Also, ax.patches will give you the bars that you would get with ax.bar(...). In case you want to apply the functions of #SaturnFromTitan or techniques of others.
I needed the bar labels too, note that my y-axis is having a zoomed view using limits on y axis. The default calculations for putting the labels on top of the bar still works using height (use_global_coordinate=False in the example). But I wanted to show that the labels can be put in the bottom of the graph too in zoomed view using global coordinates in matplotlib 3.0.2. Hope it help someone.
def autolabel(rects,data):
"""
Attach a text label above each bar displaying its height
"""
c = 0
initial = 0.091
offset = 0.205
use_global_coordinate = True
if use_global_coordinate:
for i in data:
ax.text(initial+offset*c, 0.05, str(i), horizontalalignment='center',
verticalalignment='center', transform=ax.transAxes,fontsize=8)
c=c+1
else:
for rect,i in zip(rects,data):
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2., height,str(i),ha='center', va='bottom')
I was trying to do this with stacked plot bars. The code that worked for me was.
# Code to plot. Notice the variable ax.
ax = df.groupby('target').count().T.plot.bar(stacked=True, figsize=(10, 6))
ax.legend(bbox_to_anchor=(1.1, 1.05))
# Loop to add on each bar a tag in position
for rect in ax.patches:
height = rect.get_height()
ypos = rect.get_y() + height/2
ax.text(rect.get_x() + rect.get_width()/2., ypos,
'%d' % int(height), ha='center', va='bottom')
Simply add this:
for i in range(len(y)):
plt.text(x= y[i],y= i,s= y[i], c='b')
for every item in the list(y), print the value(s) as blue-colored text on the plot in the position specified (x=position on x-axis and y=position on y-axis)
Check this link
Matplotlib Gallery
This is how I used the code snippet of autolabel.
def autolabel(rects):
"""Attach a text label above each bar in *rects*, displaying its height."""
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 3), # 3 points vertical offset
textcoords="offset points",
ha='center', va='bottom')
temp = df_launch.groupby(['yr_mt','year','month'])['subs_trend'].agg(subs_count='sum').sort_values(['year','month']).reset_index()
_, ax = plt.subplots(1,1, figsize=(30,10))
bar = ax.bar(height=temp['subs_count'],x=temp['yr_mt'] ,color ='g')
autolabel(bar)
ax.set_title('Monthly Change in Subscribers from Launch Date')
ax.set_ylabel('Subscriber Count Change')
ax.set_xlabel('Time')
plt.show()

Categories

Resources