I am wanting to add a legend to the graph below and download it as a pdf. The code I have for the graph is below.
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
mta = pd.read_csv('../project/all_mta_data_cleanded.csv') # mta data cleanded into similare catagories
cata = pd.read_csv('../project/mta_catagories_breakdown.csv') #document combining all of the catagories
weather = pd.read_csv('../project/New York Tempeture Data.csv')
mta['Total Lost Items'] = mta['Total Lost Items'] = (mta['Accessories']+ mta['Books'] + mta['Bags'] + mta['Cellphones'] + mta['Clothing'] + mta['Money'] + mta['Eletronics'] + mta['Entrainment'] + mta['Glasses'] + mta['Shoes'] + mta['Household Items'] + mta['Indentification'] + mta['Jewlery'] + mta['Keys'] + mta['Medical Equipment'] + mta['Miscellaneous'] + mta['Instruments'] + mta['NYCT Equipment'] + mta['Sports Equipment'] + mta['Tickets'] + mta['Tools'] + mta['Toys'] + mta['Wallets/Purses'])
clear = mta.iloc[[13, 40,68,92,115,138,157,176,200,222,241,245,246,250],:] #selected the last pull of each month
compl = pd.merge(clear,weather, left_on='Date',right_on='Time',how='outer').drop(columns=['Time'])
fig, ax1 = plt.subplots()
ax1.plot(compl['Date'], compl['Temp'] ,color = 'red',marker='o')
ax2= ax1.twinx()
ax2.plot(compl['Date'], compl['Total Lost Items'],color= 'purple',marker='^')
ax1.set_ylabel('Tempeture in Fahrenheit', )
for tick in ax1.get_xticklabels():
tick.set_rotation(90)
ax2.set_ylabel('Number Of Items Lost')
ax1.set_title('Average Weather In New Your City vs Total Items Lost Each Month')
plt.set_legend()
plt.figure.savefig('Project Figure.pdf')```
to add a legend to your graph you have to specify the field "label" in plt.plot(), use plt.legend() and plt.show()
fig, ax1 = plt.subplots()
l1 = ax1.plot(compl['Date'], compl['Temp'] ,color = 'red',marker='o', label = 'label_1')
ax2= ax1.twinx()
l2 = ax2.plot(compl['Date'], compl['Total Lost Items'],color= 'purple',marker='^', label = 'label_2')
ax1.set_ylabel('Temperature in Fahrenheit')
for tick in ax1.get_xticklabels():
tick.set_rotation(90)
ax2.set_ylabel('Number Of Items Lost')
ax1.set_title('Average Weather In New Your City vs Total Items Lost Each Month')
plt.legend([l1,l2],['lab1', 'lab2'])
plt.show()
plt.savefig('Project Figure.pdf')
Related
I am trying to create a graph that takes the averages from the below lines and plot them on the same new graph of the same nature.
fig, ax = plt.subplots(1,1, figsize=(10,12))
yticks = np.arange(nchan) * 0.2
lines_BC = plt.plot(resampled_BC.T + yticks[np.newaxis], label = "BC", c='black')
lines_CP = plt.plot(resampled_CP.T + yticks[np.newaxis], label = "CP", c='red')
lines_CR = plt.plot(resampled_CR.T + yticks[np.newaxis], label = "CR", c='cyan')
lines_DC = plt.plot(resampled_DC.T + yticks[np.newaxis], label = "DC", c='blue')
lines_JC = plt.plot(resampled_JC.T + yticks[np.newaxis], label = "JC", c='lime')
ax.set_yticks(yticks)
ax.set_yticklabels(muscles)
ax.set_ylabel('Muscles')
ax.set_xlabel('Time (ms)')
leg = ax.legend([lines_BC[0]] + [lines_CP[0]] + [lines_CR[0]] + [lines_DC[0]] + [lines_JC[0]], ['BC', 'CP', 'CR', 'DC', 'JC'], loc='upper right')
plt.show()
I have tried using np.mean but to no luck.
newby question.
I would like to add a new sheet to an existing wb that I've created with xlwings.
It seems that when I try to add e write the 2nd sheet the 1st one going to be overwritten.
Here the code :
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns # library for visualization
sns.set() # this command sets the seaborn chart style as the default
import xlwings as xw
from datetime import datetime
df=pd.read_excel('aspire_1909.xls')
df2=df.drop([0,2])
new_header = df2.iloc[1]
df2 = df2[2:]
df2.columns = new_header
df2=df2.set_index('User')
wb = xw.Book()
sht = wb.sheets[0]
sht.name = "Aspire Manager Graph"
sht.range('R1').value = df3
started=len(df3.loc[df3['Manager Review'] == 'Started'])
complete = len(df3.loc[df3['Manager Review'] == 'Complete'])
complete_reopened = len(df3.loc[df3['Manager Review'] == 'Complete (Reopened)'])
not_started = len(df3.loc[df3['Manager Review'] == 'Not Started'])
past_due = len(df3.loc[df3['Manager Review'] == 'Past Due'])
def insert_heading(rng,text):
rng.value = text
rng.font.bold = True
rng.font.size = 24
rng.font.color = (0,0,139)
insert_heading(sht.range("A2"),f"ASPIRE YEAR END REVIEW - MANAGER STATUS del {datetime.today().strftime('%d-%m-%Y')}")
data = {'Not Started':not_started, 'Started':started, 'Completed':complete,'Reopened' : complete_reopened,'Past Due ' : past_due }
status = list(data.keys())
values = list(data.values())
x_labels = list(a + ' ' + str(b) for (a, b) in zip(status, values))
fig = plt.figure(figsize = (10, 5))
# creating the bar plot
fig, ax = plt.subplots(figsize=(15, 15))
bars = ax.bar(status, values, color =['red','blue','green','yellow','violet'],
width = 0.4)
ax.bar_label(bars, fmt="%d", fontsize=26, rotation=0, padding=3)
plt.bar(status, values, color =['red','blue','green','yellow','violet'],
width = 0.4)
plt.xticks(status, x_labels)
plt.xticks(rotation = 45, fontsize = 13)
plt.xlabel("Year End Review Completion Status")
plt.ylabel("No Users",rotation=45,fontsize = 13)
plt.title("Aspire Mgr Year End Review")
plt.show()
sht.pictures.add(fig,
name = "Aspire Mgr Status Graph",
update = True,
left =sht.range("A4").left,
top = sht.range("A4").top,
height= 500,
width= 700)
sht1 = wb.sheets[0]
wb.sheets.add('Aspire Employees Graph')
sht1.range('R1').value = df2
started=len(df2.loc[df2['Aspire year-end reflection (FY22)'] == 'Started'])
complete = len(df2.loc[df2['Aspire year-end reflection (FY22)'] == 'Complete'])
complete_reopened = len(df2.loc[df2['Aspire year-end reflection (FY22)'] == 'Complete (Reopened)'])
not_started = len(df2.loc[df2['Aspire year-end reflection (FY22)'] == 'Not Started'])
past_due = len(df2.loc[df2['Aspire year-end reflection (FY22)'] == 'Past Due'])
def insert_heading(rng,text):
rng.value = text
rng.font.bold = True
rng.font.size = 24
rng.font.color = (0,0,139)
insert_heading(sht1.range("A2"),f"ASPIRE YEAR END REVIEW EMPLOYEE STATUS del {datetime.today().strftime('%d-%m-%Y')}")
data = {'Not Started':not_started, 'Started':started, 'Completed':complete,'Reopened' : complete_reopened,'Past Due ' : past_due }
status = list(data.keys())
values = list(data.values())
x_labels = list(a + ' ' + str(b) for (a, b) in zip(status, values))
fig = plt.figure(figsize = (10, 5))
# creating the bar plot
fig, ax = plt.subplots(figsize=(15, 15))
bars = ax.bar(status, values, color =['red','blue','green','yellow','violet'],
width = 0.4)
ax.bar_label(bars, fmt="%d", fontsize=26, rotation=0, padding=3)
plt.bar(status, values, color =['red','blue','green','yellow','violet'],
width = 0.4)
plt.xticks(status, x_labels)
plt.xticks(rotation = 45, fontsize = 13)
plt.xlabel("Year End Review Completion Status")
plt.ylabel("Nb. Users",rotation=45,fontsize = 13)
plt.title("Aspire Employee Year End Review")
plt.show()
sht1.pictures.add(fig,
name = "Aspire Employee Status Graph",
update = True,
left =sht.range("A4").left,
top = sht.range("A4").top,
height= 500,
width= 700)
Could someone would be able to help me get what Is wrong ? ( I know ,almost everything :-) )
Thanks a lot in advance
In the second half of the code you have:
sht1 = wb.sheets[0]
wb.sheets.add('Aspire Employees Graph')
sht1.range('R1').value = df2
What wb.sheets[0] is returning is the very first sheet of the workbook. Towards the beginning you have the first section, which is:
sht = wb.sheets[0]
sht.name = "Aspire Manager Graph"
sht.range('R1').value = df3
As you use wb.sheets[0] both times, but haven't inserted a sheet at the beginning, you are just referring to the same sheet. The addition of the new sheet is correct, but you haven't set that as variable sht1.
Instead, for the second section, you could re-write to the following, combining the two lines into one so that the variable is the correct sheet:
sht1 = wb.sheets.add('Aspire Employees Graph')
sht1.range('R1').value = df2
Edit
To change the colour of the sheet tab:
sht1.api.Tab.ColorIndex = 3
The full list of colours can be found in the VBA ColorIndex documentation.
For more specific colours, see the answers to this question.
Hello everyone how can i make legend for 3 different bar color that code with subplot?
Data frame:
This is my code:
fig,axs = plt.subplots(2,3, figsize=(30,20))
axs[0,1].bar(x = df_7_churn_tenure['Kategori'],height = df_7_churn_tenure['Jumlah Churn'],color = ['lightsalmon','maroon','darkorange'])
axs[0,1].legend(['Low Tenure = x<24','Medium Tenure = 24<= x <=48','High Tenure = x >=48'],loc='best',fontsize=12)
plt.show()
And the result for barplot legend only shows 1 label like this:
Is there any solution to shows all of my legend?
Try this:
fig,axs = plt.subplots(2,3, figsize=(30,20))
axs[0,1].bar(x = df_7_churn_tenure['Kategori'],height = df_7_churn_tenure['Jumlah Churn'],color ['lightsalmon','maroon','darkorange'])
axs = axs[0,1]
lns1 = axs.plot('-',label = 'Low Tenure = x<24')
lns2 = axs.plot('-',label = 'Medium Tenure = 24<= x <=48')
lns3 = axs.plot('-',label = 'High Tenure = x >=48')
# added these three lines
lns = lns1+lns2+lns3
labs = [l.get_label() for l in lns]
axs.legend(lns, labs,loc=0)
plt.show()
I need to copy the bar chart in the image with python.
bar chart I have to copy
What I have been able to achieve is next image.
bar chart I have achieved
And the code I have used is:
import matplotlib.pyplot as plt
ausgaben = 130386
einnahmen = 147233
profit = einnahmen-ausgaben
titles = ["Ausgaben", "Profit", "Einnahmen"]
euros = [ausgaben, profit, einnahmen]
colors = ['#6F8CA7', '#F6BC06', '#59908F']
dummysum1 = []
dummysum2 = []
for i in range(len(euros)):
dummysum1.append(euros[i]+4000)
dummysum2.append(max(euros)+15000)
if euros[1] > 0:
dummysum1[1] = euros[1]+4000
if euros[1] <= 0:
dummysum1[1] = 4000
position1 = (euros[0]+euros[2])/2
percentile = (euros[2]-euros[0])/euros[0]*100
if percentile > 0:
label0 = '+{:.1f}%'.format(percentile)
else:
label0 = '{:.1f}%'.format(percentile)
fig, ax = plt.subplots(figsize=(7, 5))
fig.set_facecolor('#D0A210')
fig.patch.set_alpha(0.2)
ax.bar(titles[0], euros[0], alpha=0.6, color=colors[0])
ax.bar(titles[1], euros[1], alpha=0.6, color=colors[1])
ax.bar(titles[2], euros[2], alpha=0.6, color=colors[2])
plt.axhline(y=euros[0], color='#BCBCBC')
plt.axhline(y=euros[2], color='#BCBCBC')
ax.set_facecolor('#D0A210')
ax.patch.set_alpha(0.02)
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
ax.spines.right.set_visible(False)
ax.spines.left.set_visible(False)
ax.spines.top.set_visible(False)
ax.spines.bottom.set_visible(False)
ax.text(titles[0], dummysum1[0], '{} €'.format(euros[0]), horizontalalignment='center')
ax.text(titles[1], dummysum1[1], '{} €'.format(euros[1]), horizontalalignment='center')
ax.text(titles[2], dummysum1[2], '{} €'.format(euros[2]), horizontalalignment='center')
ax.text(2.58, position1-1000, label0)
ax.text(titles[0], dummysum2[0], titles[0], horizontalalignment='center')
ax.text(titles[1], dummysum2[1], titles[1], horizontalalignment='center')
ax.text(titles[2], dummysum2[2], titles[2], horizontalalignment='center')
plt.show()
. How can I get the yellow bar chart starting at y=130386 instead of y=0 and the yellow arrow at the right hand side?
(The first question is the most important!)
Thank you all!
For the first question, just add a value for the bottom parameter. I have also added the arrow using annotate:
import matplotlib.pyplot as plt
ausgaben = 130386
einnahmen = 147233
profit = einnahmen-ausgaben
titles = ["Ausgaben", "Profit", "Einnahmen"]
euros = [ausgaben, profit, einnahmen]
colors = ['#6F8CA7', '#F6BC06', '#59908F']
dummysum1 = []
dummysum2 = []
for i in range(len(euros)):
dummysum1.append(euros[i]+4000)
dummysum2.append(max(euros)+15000)
if euros[1] > 0:
dummysum1[1] = euros[1]+4000
if euros[1] <= 0:
dummysum1[1] = 4000
position1 = (euros[0]+euros[2])/2
percentile = (euros[2]-euros[0])/euros[0]*100
if percentile > 0:
label0 = '+{:.1f}%'.format(percentile)
else:
label0 = '{:.1f}%'.format(percentile)
fig, ax = plt.subplots(figsize=(7, 5))
fig.set_facecolor('#D0A210')
fig.patch.set_alpha(0.2)
ax.bar(titles[0], euros[0], alpha=0.6, color=colors[0])
ax.bar(titles[1], euros[1], alpha=0.6, color=colors[1], bottom=ausgaben)
ax.bar(titles[2], euros[2], alpha=0.6, color=colors[2])
plt.axhline(y=euros[0], color='#BCBCBC')
plt.axhline(y=euros[2], color='#BCBCBC')
ax.set_facecolor('#D0A210')
ax.patch.set_alpha(0.02)
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
ax.spines.right.set_visible(False)
ax.spines.left.set_visible(False)
ax.spines.top.set_visible(False)
ax.spines.bottom.set_visible(False)
ax.text(titles[0], dummysum1[0], '{} €'.format(euros[0]), horizontalalignment='center')
ax.text(titles[1], dummysum1[1]+ausgaben, '{} €'.format(euros[1]), horizontalalignment='center')
ax.text(titles[2], dummysum1[2], '{} €'.format(euros[2]), horizontalalignment='center')
ax.text(2.58, position1-1000, label0)
ax.text(titles[0], dummysum2[0], titles[0], horizontalalignment='center')
ax.text(titles[1], dummysum2[1], titles[1], horizontalalignment='center')
ax.text(titles[2], dummysum2[2], titles[2], horizontalalignment='center')
ax.annotate("", xy=(2.5, ausgaben+profit*1.05), xytext=(2.5, ausgaben), arrowprops=dict(arrowstyle="->", color="orange", lw=2.0))
plt.show()
I am getting a very strange error using basemap. No error appears, yet my 3rd plot has no data plotted when data does indeed exist. Below is my code. When run, you will see that both modis and seawifs data is plotted, but viirs is not. I can't figure out why.
import numpy as np
import urllib
import urllib2
import netCDF4
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from datetime import datetime, date, time, timedelta
import json
import math
def indexsearch(datebroken,year, month, day):
for i in range(0,len(datebroken)):
if (datebroken[i,0] == year and datebroken[i,1] == month and datebroken[i,2] == day):
return i
url = 'http://coastwatch.pfeg.noaa.gov/erddap/griddap/erdMWchlamday.nc?chlorophyll' +\
'[(2002-07-16T12:00:00Z):1:(2015-04-16T00:00:00Z)][(0.0):1:(0.0)][(36):1:(39)][(235):1:(240)]'
file = 'erdMWchlamday.nc'
urllib.urlretrieve(url, file)
ncfilemod = netCDF4.Dataset(file)
ncv1 = ncfilemod.variables
print ncv1.keys()
time1=ncv1['time'][:]
inceptiondate = datetime(1970, 1, 1, 0, 0, 0)
timenew1=[]
for i in time1[:]:
newdate = inceptiondate + timedelta(seconds=i)
timenew1.append(newdate.strftime('%Y%m%d%H'))
datebroken1 = np.zeros((len(timenew1),4),dtype=int)
for i in range(0,len(timenew1)):
datebroken1[i,0] = int(timenew1[i][0:4])
datebroken1[i,1] = int(timenew1[i][4:6])
datebroken1[i,2] = int(timenew1[i][6:8])
datebroken1[i,3] = int(timenew1[i][8:10])
lon1= ncv1['longitude'][:]
lat1 = ncv1['latitude'][:]
lons1, lats1 = np.meshgrid(lon1,lat1)
chla1 = ncv1['chlorophyll'][:,0,:,:]
url = 'http://coastwatch.pfeg.noaa.gov/erddap/griddap/erdSWchlamday.nc?chlorophyll' +\
'[(1997-09-16):1:(2010-12-16T12:00:00Z)][(0.0):1:(0.0)][(36):1:(39)][(235):1:(240)]'
file = 'erdSWchlamday.nc'
urllib.urlretrieve(url, file)
#Ncfile 2
ncfilewif = netCDF4.Dataset(file)
ncv2 = ncfilewif.variables
print ncv2.keys()
time2=ncv2['time'][:]
inceptiondate = datetime(1970, 1, 1, 0, 0, 0)
timenew2=[]
for i in time2[:]:
newdate = inceptiondate + timedelta(seconds=i)
timenew2.append(newdate.strftime('%Y%m%d%H'))
datebroken2 = np.zeros((len(timenew2),4),dtype=int)
for i in range(0,len(timenew2)):
datebroken2[i,0] = int(timenew2[i][0:4])
datebroken2[i,1] = int(timenew2[i][4:6])
datebroken2[i,2] = int(timenew2[i][6:8])
datebroken2[i,3] = int(timenew2[i][8:10])
lon2= ncv2['longitude'][:]
lat2 = ncv2['latitude'][:]
lons2, lats2 = np.meshgrid(lon2,lat2)
chla2 = ncv2['chlorophyll'][:,0,:,:]
url = 'http://coastwatch.pfeg.noaa.gov/erddap/griddap/erdVH2chlamday.nc?chla' +\
'[(2012-01-15):1:(2015-05-15T00:00:00Z)][(39):1:(36)][(-125):1:(-120)]'
file = 'erdVH2chlamday.nc'
urllib.urlretrieve(url, file)
ncfileviir = netCDF4.Dataset(file)
ncv3 = ncfileviir.variables
print ncv3.keys()
time3=ncv3['time'][:]
inceptiondate = datetime(1970, 1, 1, 0, 0, 0)
timenew3=[]
for i in time3[:]:
newdate = inceptiondate + timedelta(seconds=i)
timenew3.append(newdate.strftime('%Y%m%d%H'))
datebroken3 = np.zeros((len(timenew3),4),dtype=int)
for i in range(0,len(timenew3)):
datebroken3[i,0] = int(timenew3[i][0:4])
datebroken3[i,1] = int(timenew3[i][4:6])
datebroken3[i,2] = int(timenew3[i][6:8])
datebroken3[i,3] = int(timenew3[i][8:10])
lon3= ncv3['longitude'][:]
lat3 = ncv3['latitude'][:]
lons3, lats3 = np.meshgrid(lon3,lat3)
chla3 = ncv3['chla'][:,:,:]
i1=indexsearch(datebroken1,2012,6,16)
print i1
i2=indexsearch(datebroken2,2010,6,16)
print i2
i3=indexsearch(datebroken3,2012,6,15)
print i3
chla1plot = chla1[i1,:,:]
chla2plot = chla2[i2,:,:]
chla3plot = chla3[i3,:,:]
ncfileviir.close()
ncfilemod.close()
ncfilewif.close()
Important code is below here. All code above is just pulling the data into python to plot.
minlat = 36
maxlat = 39
minlon = 235
maxlon = 240
# Create map
fig = plt.figure()
#####################################################################################################################
#plot figure 1
ax1 = fig.add_subplot(221)
m = Basemap(projection='merc', llcrnrlat=minlat,urcrnrlat=maxlat,llcrnrlon=minlon, urcrnrlon=maxlon,resolution='h')
cs1 = m.pcolormesh(lons1,lats1,chla1plot,cmap=plt.cm.jet,latlon=True)
m.drawcoastlines()
m.drawmapboundary()
m.fillcontinents()
m.drawcountries()
m.drawstates()
m.drawrivers()
#Sets up parallels and meridians.
parallels = np.arange(36.,39,1.)
# labels = [left,right,top,bottom]
m.drawparallels(parallels,labels=[False,True,True,False])
meridians = np.arange(235.,240.,1.)
m.drawmeridians(meridians,labels=[True,False,False,True])
ax1.set_title('Modis')
#####################################################################################################################
#plot figure 2
ax2 = fig.add_subplot(222)
cs2 = m.pcolormesh(lons2,lats2,chla2plot,cmap=plt.cm.jet,latlon=True)
m.drawcoastlines()
m.drawmapboundary()
m.fillcontinents()
m.drawcountries()
m.drawstates()
m.drawrivers()
#Sets up parallels and meridians.
parallels = np.arange(36.,39,1.)
# labels = [left,right,top,bottom]
m.drawparallels(parallels,labels=[False,True,True,False])
meridians = np.arange(235.,240.,1.)
m.drawmeridians(meridians,labels=[True,False,False,True])
ax2.set_title('SeaWIFS')
#####################################################################################################################
#plot figure 3
ax3 = fig.add_subplot(223)
cs3 = m.pcolormesh(lons3,np.flipud(lats3),np.flipud(chla3plot),cmap=plt.cm.jet,latlon=True)
m.drawcoastlines()
m.drawmapboundary()
m.fillcontinents()
m.drawcountries()
m.drawstates()
m.drawrivers()
#Sets up parallels and meridians.
parallels = np.arange(36.,39,1.)
# labels = [left,right,top,bottom]
m.drawparallels(parallels,labels=[False,True,True,False])
meridians = np.arange(235.,240.,1.)
m.drawmeridians(meridians,labels=[True,False,False,True])
ax3.set_title('VIIRS')
# Save figure (without 'white' borders)
#plt.savefig('SSTtest.png', bbox_inches='tight')
plt.show()
My results are shown here!
![results]: http://i.stack.imgur.com/dRjkU.png
The issue that I found was that I had
minlat = 36
maxlat = 39
minlon = 235
maxlon = 240
m = Basemap(projection='merc', llcrnrlat=minlat,urcrnrlat=maxlat,llcrnrlon=minlon, urcrnrlon=maxlon,resolution='h')
The final plot was -125 to -120 which basemap did not automatically handle, but instead placed the plot at an area where I did not have data. I added a new m = basemap statement and changed the meridian numbers for the third graph using -125 to -120 as my longitude and the graph plotted just fine.