def plot_pie(self, nx_dataframe, topic, se_title, kurs): gender = self.sort_column(nx_dataframe[topic]) labels = [gender[0][i] for i,elem in enumerate(gender[0])] fracs = [gender[1][i] for i,elem in enumerate(gender[1])] explode = [0.05 for i,elem in enumerate(gender[1])] plt.pie(fracs, explode=explode, labels=labels, autopct='%.0f%%', shadow=True) plt.savefig('./PDFcreater/Plots/{}/1{}.png'.format(kurs,se_title)) plt.clf() plt.cla() plt.close()
def comparision_piechart(username):##function declaration to show number of positive and negative comments and plot a pie-chart media_id = fetch_post_id(username) request_url = (BASE_URL + 'media/%s/comments/?access_token=%s') % (media_id, app_access_token) print 'GET request url : %s' % (request_url) comment_info = requests.get(request_url).json() if comment_info['meta']['code'] == 200: if len(comment_info['data']): for x in range(0, len(comment_info['data'])): comment_id = comment_info['data'][x]['id'] comment_text = comment_info['data'][x]['text'] blob = TextBlob(comment_text, analyzer=NaiveBayesAnalyzer()) if (blob.sentiment.p_neg > blob.sentiment.p_pos): print 'Negative comment : %s' % (comment_text) for y in range(0, len(comment_info['data'])): comment_id = comment_info['data'][y]['id'] comment_text = comment_info['data'][y]['text'] blob = TextBlob(comment_text, analyzer=NaiveBayesAnalyzer()) if (blob.sentiment.p_neg < blob.sentiment.p_pos): print 'positive comment : %s' % (comment_text) a = y + 1 # positive comments b = x - y # negative comments print "No. of Positive comments: %s" % (a) print "No. of negative comments: %s" % (b) c = a + b print "Total no. of comments: %s" %(c) #commands to plot pychart labels = 'Positive ', 'Negative' sizes = [a, b] colors = ['blanchedalmond', 'aliceblue'] explode = (0.1, 0) # explode 1st slice plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=140) plt.axis('equal') plt.show() else: print 'Comments not found on the post!' else: print 'Status code other than 200 received!'
def fetch(Handle): root.destroy() summary = { "Compilation": 0, "Runtime": 0, "Wrong": 0, "Accepted": 0, "Time": 0 } url = "https://codeforces.com/submissions/" + Handle + "/page/" source = req.get(url + "1") soup = bs(source.text, "lxml") no = len(soup.find_all("span", class_="page-index")) page_no = i = 1 while page_no <= no: source = req.get(url + str(page_no)) soup = bs(source.text, "lxml") table = soup.find_all("tr") page_no = page_no + 1 for tag in range(26, len(table) - 1): required = table[tag].find_all("td", class_="status-small") contest_name = required[1].a.text.strip() try: result = required[2].span.span.text except: result = required[2].span.text result = result.split(" ") length = len(result) if length == 1: print(Fore.GREEN + str(i) + " : " + contest_name) if length == 2: print(Fore.CYAN + str(i) + " : " + contest_name) if length == 6: print(Fore.BLUE + str(i) + " : " + contest_name) if length == 5: if result[0] == "Wrong": print(Fore.RED + str(i) + " : " + contest_name) else: print(Fore.WHITE + str(i) + " : " + contest_name) summary[result[0]] += 1 print(Style.RESET_ALL, end="") i = i + 1 plt.axis("equal") plt.pie(summary.values(), labels=summary.keys(), autopct=None) plt.show()
def getHistogram2PGN(df): y = df.iloc[:, -1] c = Counter(y) numDiffClasses = len(y.unique()) target_names = y.unique() colors = colors = ['lightcoral', 'gold', 'yellowgreen', 'cyan'][:numDiffClasses] plt.rcParams["figure.figsize"] = [10, 5] plt.pie([c[i] / len(y) * 100.0 for i in c], labels=target_names, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90) plt.axis('equal') plt.title(df.columns.values[-1]) path = WORKING_PATH + "/___circle_labels.png" plt.savefig(path) plt.clf() return path
def pieChart(df): stress_groups = df.groupby("Stress") one_ser = stress_groups.get_group(1) two_ser = stress_groups.get_group(2) three_ser = stress_groups.get_group(3) four_ser = stress_groups.get_group(4) five_ser = stress_groups.get_group(5) six_ser = stress_groups.get_group(6) seven_ser = stress_groups.get_group(7) eight_ser = stress_groups.get_group(8) nine_ser = stress_groups.get_group(9) plt.figure(figsize=(8,8)) # define x and y values xs = [1, 2, 3, 4,5, 6, 7, 8, 9] ys = [len(one_ser),len(two_ser),len(three_ser),len(four_ser),len(five_ser),len(six_ser),len(seven_ser),len(eight_ser),len(nine_ser),] #giving plot a label for clarity plt.title('Percent of days at stress levels (1-9)') #creating pie chart plt.pie(ys, labels=xs, autopct="%1.1f%%") plt.show()
#plotting the pollutant data with the help of bar chart pollutants = [i for i in iaqi] values = [i['v'] for i in iaqi.values()] # Exploding the first slice explode = [0 for i in pollutants] mx = values.index(max(values)) # explode 1st slice explode[mx] = 0.1 # Plot a pie chart plt.figure(figsize=(8, 6)) plt.pie(values, labels=pollutants, explode=explode, autopct='%1.1f%%', shadow=True) plt.title('Air pollutants and their probable amount in atmosphere [India]') plt.axis('equal') plt.show() # # showing INDIA AQI on world map using cartopy # In[82]: import cartopy.crs as ccrs # In[83]:
def main(argv): print("hello") # 读取表格 data = xlrd.open_workbook("developers.xlsx") # 获取表格的sheets table = data.sheets()[0] # 输出行数量 print(table.nrows) # 8 # 输出列数量 print(table.ncols) # 4 # 获取第一行数据 row1data = table.row_values(0) print(row1data) # ['列1', '列2', '列3', '列4'] print(row1data[0]) # 列1 from pyecharts.charts import Bar # 读取表格 # data = xlrd.open_workbook("developers.xlsx") # 获取表格的sheets table = data.sheets()[0] # 输出行数量 print(table.nrows) # 输出列数量 print(table.ncols) # 获取第一行数据 row1data = table.row_values(0) print(row1data) # ['列1', '列2', '列3', '列4'] print(row1data[0]) # 列1 xdata = [] ydata = [] for i in range(1, table.nrows): print(table.row_values(i)) xdata.append(table.row_values(i)[0]) ydata.append(table.row_values(i)[1]) print(xdata) print(ydata) # 数据可视化,柱状图 bar = Bar() bar.add_xaxis(xdata) bar.add_yaxis("名称1", ydata) bar.render("show.html") plt.bar(xdata, ydata) x = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019] y = [5, 3, 6, 20, 17, 16, 19, 30, 32, 35] plt.plot(x, y) plt.show() a = np.random.randn(100) s = pd.Series(a) plt.hist(s) plt.show() x = ['Cat1', 'Cat2', 'Cat3', 'Cat4', 'Cat5'] y = [5, 4, 8, 12, 7] plt.bar(x, y) plt.show() x = ['Cat1', 'Cat2', 'Cat3', 'Cat4', 'Cat5'] y = [5, 4, 8, 12, 7] plt.barh(x, y) plt.show() nums = [25, 37, 33, 37, 6] labels = ['High-school', 'Bachelor', 'Master', 'Ph.d', 'Others'] plt.pie(x=nums, labels=labels) plt.show() # 生成0-1之间的10*4维度数据 data = np.random.normal(size=(10, 4)) lables = ['A', 'B', 'C', 'D'] # 用Matplotlib画箱线图 plt.boxplot(data, labels=lables) plt.show() # flights = sns.load_dataset("flights") # data = flights.pivot('year', 'month', 'passengers') # sns.heatmap(data) # plt.show() N = 1000 x = np.random.randn(N) y = np.random.randn(N) plt.scatter(x, y, marker='x') plt.show() N = 10000 x = np.random.randn(N) y = np.random.randn(N) plt.scatter(x, y, marker='x') plt.show() labels = np.array([u"推进", "KDA", u"生存", u"团战", u"发育", u"输出"]) stats = [83, 61, 95, 67, 76, 88] # 画图数据准备,角度、状态值 angles = np.linspace(0, 2 * np.pi, len(labels), endpoint=False) stats = np.concatenate((stats, [stats[0]])) angles = np.concatenate((angles, [angles[0]])) # 用Matplotlib画蜘蛛图 fig = plt.figure() ax = fig.add_subplot(111, polar=True) ax.plot(angles, stats, 'o-', linewidth=2) ax.fill(angles, stats, alpha=0.25) # 设置中文字体 # font = FontProperties(fname=r"/System/Library/Fonts/PingFang.ttc", size=14) # ax.set_thetagrids(angles * 180/np.pi, labels, FontProperties=font) plt.show() # tips = sns.load_dataset("tips") # tips.head(10) # # 散点图 # sns.jointplot(x="total_bill", y="tip", data=tips, kind='scatter') # # # Hexbin图 # sns.jointplot(x="total_bill", y="tip", data=tips, kind='hex') # plt.show() df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd']) # 堆面积图 df.plot.area() # 面积图 df.plot.area(stacked=False) df = pd.DataFrame(np.random.randn(1000, 2), columns=['a', 'b']) df['b'] = df['b'] + np.arange(1000) # 关键字参数gridsize;它控制x方向上的六边形数量,默认为100,较大的gridsize意味着更多,更小的bin df.plot.hexbin(x='a', y='b', gridsize=25) print("end")
typ) new1['sent_scores'] = sentscore(new1) ############################ Pie charts for top features ################################ import matplotlib.pyplot as plt title = locfeatures[6][0] imps = [ locfeatures[6][1][0][1], locfeatures[6][1][1][1], locfeatures[6][1][2][1] ] labels = [ locfeatures[6][1][0][0], locfeatures[6][1][1][0], locfeatures[6][1][2][0] ] sizes = [i / sum(imps) for i in imps] a = plt.pie(sizes, shadow=True, startangle=90) l = [ str(a) + ', ' + str(round(b * 100, 2)) + '%' for a, b in list(zip(labels, sizes)) ] plt.legend(a[0], l, bbox_to_anchor=(1.35, 0.025), loc="lower right") plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle. plt.title(title) plt.show() title = locfeatures[19][0] imps = [ locfeatures[19][1][0][1], locfeatures[19][1][1][1], locfeatures[19][1][2][1]
import matplotlib as plt import numpy as np y = np.array([35, 25, 25, 15]) mylabels = ['Apples', 'Bananas', 'Charries', 'Dates'] myexplode = [0.2, 0, 0, 0] plt.pie(y, labels=mylebels, explode=myexplode, shadow=True)
# These codes are adapted from the lecture PowerPoint, thanks for providing these useful examples. # And I also look for online sources to undestand their meanings. # import the library for pie chart # Note: only import matplotlib is nut enough for making piechart import matplotlib.pyplot as plt #This definition represents the label of different color parts of the pie chart. labels = 'USA', 'India', 'Brazil', 'Russia', 'UK' # This definition represents the size of each part, indicated by numbers, and also useful for calculating the percentage. sizes = [29862124, 11285561, 11205972, 4360823, 4234924] # This definition indicates that how long certian parts is away from the main part of pie chart. explode = (0, 0, 0, 0, 0) # Combine all indexs together then make a pie chart. # Note1: shadow indicates the shadow part of the pie chart (if True, then pie chart will have a shadow). # Note2: startangle indicates the direction of the pie chart (i.e., if values changed, then the pie chart will rotate.). # Note3: autpct is used to calculated percentage, and also label them on the pie chart. # Note4: colors is used to change the color of pie chart. plt.pie(sizes, explode=explode, labels=labels, shadow=False, startangle=90, autopct='%1.1F%%', colors=['C9', 'C2', 'C1', 'C6', 'C4']) # Make sure that x,y axis have the same scale plt.axis('equal') # give this piechart a title plt.title('Cases of five counties', size=20) # To show user the pie chart plt.show()
def bar(x,y,height,corr_hq, corr_lq, incorr_hq, incorr_lq): p = plt.pie([corr_hq,corr_lq,incorr_hq,incorr_lq] , colors=["#FFC531","#58D452","#70DB1D","#8AE444"] , radius=radius) return mpl.collections.PatchColleckkktion(p)
def main(): driver = webdriver.Chrome('/Users/Taras/bin/chromedriver') driver.get("https://www.linkedin.com/jobs") url = driver.current_url newURL = urllib.parse.unquote(url) print(newURL) if newURL != "https://www.linkedin.com/jobs/?trk=jobs-home-jobsfe-redirect": print("hello") signIn = urllib.parse.unquote("https://www.linkedin.com/uas/login?session_redirect=https%3A%2F%2Fwww%2Elinkedin%2Ecom%2Fjobs%2F%3Ftrk%3Djobs-home-jobsfe-redirect&fromSignIn=true&trk=uno-reg-join-sign-in") driver.get(signIn) email = driver.find_element_by_name("session_key") email.send_keys("*****@*****.**") pwd = driver.find_element_by_name("session_password") pwd.send_keys("Leroyiheanacho19$") signInBtn = driver.find_element_by_name("signin") signInBtn.click() collect(driver) #logIn = driver.find_element_by_class_name("form-toggle") #logIn.click() assert "in" in driver.title elem = driver.find_element_by_name("keywords") #elem = driver.find_element_by_xpath("//input[@placeholder='Search jobs by title, keyword or company']") elem2 = driver.find_element_by_class_name("location-clear-icon") #elem3 = driver.find_element_by_xpath("//input[@placeholder='City, state, postal code or country']") elem3 = driver.find_element_by_name("location") jobSearch = input("What keyword would you like to search for? ") locSearch = input("Where would you like to run this search on? ") print("Running a search on the position of " + jobSearch + " in " + locSearch + ".") #elem.clear() elem2.click() elem.send_keys(jobSearch) elem3.send_keys(locSearch) elem.send_keys(Keys.RETURN) #button = driver.find_element_by_xpath("//button[text()='Search']") #button.click() assert "No results found." not in driver.page_source plList = ['Java','C','C++','C#','Python','PHP','Javascript','Visual Basic', 'VB','.NET','Perl','Ruby', 'R','Delphi','Swift','Assembly','Go','Objective-C','PL','SQL','Scratch','Dart','SAS','D','COBOL', 'Ada','Erlang','Lisp','Prolog','LabVIEW', 'HTML','CSS','JQuery','ASP','Groovy','Clojure','Script','Node','Mongo'] linkElements = driver.find_elements_by_class_name("job-title-link") links = [] for a in linkElements: linkHref= a.get_attribute("href") links.append(linkHref) #print([i for i in links]) #a.send_keys(Keys.RETURN) #time.sleep(3) #driver.back() i=1 frame = pd.DataFrame( columns=[i], index=['Job Title', 'Company', 'Languages', 'Total Langs']) for link in links: driver.get(link) #jobDesc = driver.find_element_by_class_name("description-section") soup = BeautifulSoup(driver.page_source, "html.parser") jobDesc = soup.find("div", class_="description-section").text blob = TextBlob(jobDesc) #jobTitle1 = urllib.parse.unquote("h1.jobs-details-top-card__job-title.Sans-21px-black-85%-dense") jobTitle = driver.find_element_by_tag_name("h1").text companyName = driver.find_element_by_class_name("company").text companies = [] companies.append(companyName) print(companies) #print(jobTitle.text) #works -- prints job title jobs = [] jobs.append(jobTitle) print(jobs) languages = [] #results = soup.p.find_all(string=re.compile('.*{0}.*'.format(plList)), recursive=True) #print(results) count = 0 for lang in plList: if lang not in blob: continue elif lang in blob: languages.append(lang) count = count + 1 jobs = ''.join(jobs) companies = ''.join(companies) languages = ', '.join(languages) finalArr = [] finalArr.append(jobs) finalArr.append(companies) finalArr.append(languages) finalArr.append(count) frame[i] = finalArr print(frame) i = i + 1 colors = ["#E13F29", "#D69A80", "#D63B59", "#AE5552", "#CB5C3B", "#EB8076", "#96624E"] # Create a pie chart plt.pie( # using data total)arrests df['Total Langs'], # with the labels being officer names labels=df['Languages'], # with no shadows shadow=False, # with colors colors=colors, # with one slide exploded out explode=(0, 0, 0, 0, 0.15), # with the start angle at 90% startangle=90, # with the percent listed as a fraction autopct='%1.1f%%', ) # View the plot drop above plt.axis('equal') # View the plot plt.tight_layout() plt.show()
x = np.array(["A", "B", "C", "D"]) y = np.array([3, 8, 1, 10]) # plt.bar(x, y, color = "hotpink") # plt.show() # Matplotlib Bars x = np.random.normal(170, 10, 250) print(x) plt.hist(x) plt.show() # Matplotlib Pie Charts y = np.array([55, 15, 25, 10]) plt.pie(y) plt.show() # Labels y = np.array([55, 15, 25, 10]) mylabels = ["Apples", "Bananas", "Cherries", "Dates"] plt.pie(y, labels=mylabels) plt.show() # Start Angle y = np.array([55, 15, 25, 10]) mylabels = ["Apples", "Bananas", "Cherries", "Dates"] plt.pie(y, labels=mylabels, startangle=90) plt.show() # Explode
categorical = ["target", "sex", "cp", "fbs", "restecg", "exang", "slope", "ca", "thal"] plt.figure(figsize=(14,20)) for i in range(1,10): labels = data[categorical[i-1]].value_counts().index sizes = data[categorical[i-1]].value_counts().values plt.subplot(5,2,i) plt.pie(sizes, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90) plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle. plt.xticks([]) plt.yticks([]) plt.title(categorical[i-1].upper()) plt.show() plt.figure(figsize=(10,17)) plt.subplot(5,2,1) sns.kdeplot(data.loc[data["target"]==1]["age"],color="green",shade=True) sns.kdeplot(data.loc[data["target"]==0]["age"],color="red",shade=True) plt.legend(["target:1","target:0"]) plt.title("Age".upper()) for i in range(2,9): plt.subplot(5,2,i)
import matplotlib as mpl from matplotlib.gridspec import GridSpec import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') # In[23]: labels = list(data1['AgeGroup']) sizes = list(data1['TotalCases']) explode = [] for i in labels: explode.append(0.05) plt.figure(figsize= (15,10)) plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=9, explode =explode) centre_circle = plt.Circle((0,0),0.70,fc='white') fig = plt.gcf() fig.gca().add_artist(centre_circle) plt.title('India - Age Group wise Distribution',fontsize = 20) plt.axis('equal') plt.tight_layout() # ## Importing and Reading the Dataset # HospitalBedsIndia.csv # In[24]: data2 = pd.read_csv(r"D:\DATA SCIENCE\Covid19 analysis\557629_1323860_bundle_archive\HospitalBedsIndia.csv")
# Plot Pie Chart for Year 2011 Country Wise. import pandas as pd import matplotlib as plt df = pd.read_csv("BigMartSalesData.csv") df_grouped_country = df.query("Year == 2011").filter( ["Country", "Amount"]).groupby(["Country"], as_index=False).sum() plt.pie(df_grouped_country["Amount"], labels=df_grouped_country["Country"], autopct='%1.1f%%', shadow=True) plt.tight_layout() plt.show() # Which Country contributes highest towards sales? # United Kingdom
import matplotlib as plt labels = 'Python', 'C++', 'Ruby', 'Java', 'PHP', 'Pearl' sizes = {33,52,12,17,62,48} seperated = {.1,0,0,0,0,0} plt.pie(sizes, labels = labels, autopct='%1.1f%%', explode=seperated) plt.axis('equal') plt.show()
# In[13]: #ploting piechart fig = plt.figure(figsize=(15,12)) plt.suptitle('Pie Chart Distributions', fontsize=20) for i in range(1,dataset2.shape[1]+1): plt.subplot(6,3,i) f=plt.gca() f.axes.get_yaxis().set_visible(False) f.set_title(dataset2.columns.values[i-1]) values=dataset2.iloc[:,i-1].value_counts(normalize=True).values index=dataset2.iloc[:,i-1].value_counts(normalize=True).index plt.pie(values,labels=index,autopct='%1.1f%%') plt.tight_layout(rect=[0,0.03,1,0.95]) # In[14]: ## Exploring Uneven Features dataset[dataset2.waiting_4_loan==1].churn.value_counts() # In[15]: dataset[dataset2.cancelled_loan == 1].churn.value_counts()
msg = "Do you want to continue?" title = "Please Confirm" if choice=="Pie": # show a Continue/Cancel dialog pass# user chose Continue import numpy as np import matplotlib as plt import matplotlib.pyplot as plt %matplotlib inline labels='Red','Green','Yellow','Blue' x=int(input("Enter a value")) y=int(input("Enter a value")) z=int(input("Enter a value")) w=int(input("Enter a value")) sizes=[x,y,z,w] colours=['Red','Green','Yellow','Blue'] plt.pie(sizes,labels=labels) plt.axis('equal') plt.show() sys.exit(0) elif choice=="Line Graph": import matplotlib.pyplot as plt x = [1,2,3] y = [5,7,4] x2 = [1,2,3] y2 = [10,14,12] plt.plot(x,y,label='First Line') plt.plot(x2,y2,label='Second Line') plt.xlabel('Plot Number') plt.ylabel('Important Var')
print(restaurants.head()) cuisine_options_count = restaurants.cuisine.nunique() cuisine_counts = restaurants.groupby('cuisine').id.count().reset_index() restaurants = pd.read_csv('restaurants.csv') cuisine_counts = restaurants.groupby('cuisine')\ .name.count()\ .reset_index() cuisines = cuisine_counts.cuisine.values counts = cuisine_counts.name.values plt.pie(counts, labels=cuisines, autopct='%d%%') plt.title('FoodWheel') plt.axis('equal') plt.show() orders = pd.read_csv('orders.csv') print(orders.head()) month = lambda date: date.split('-')[0] orders['month'] = orders.date.apply(month) avg_order = orders.groupby('month').price.mean().reset_index() std_order = orders.groupby('month').price.std().reset_index() orders['month'] = orders.date.apply(lambda x: x.split('-')[0])
#grade b grade_b = np.sum((student[:, 31] > 80) & (student[:, 31] < 90)) print("Number of students with grade B: ") print(grade_b) #grade c grade_c = np.sum((student[:, 31] > 70) & (student[:, 31] < 80)) print("Number of students with grade C: ") print(grade_c) #grade d grade_d = np.sum((student[:, 31] > 60) & (student[:, 31] < 70)) print("Number of students with grade D: ") print(grade_d) #grade f grade_f = student[:, 31] <= 59 print("Number of students with grade F: ") print(student[grade_f, :].shape[0]) #create pie chart Grades = [21, 8, 1, 1, 2] slice_labels = [ 'Grade is A', ' Grade is B', 'Grade is C', 'Grade is D', 'Grade is F' ] explode = (0.1, 0, 0, 0, 0) #only explode A grade plt.pie(Grades, labels=slice_labels, explode=explode) plt.title('Student Grades') plt.show()