Table of contents
Draw TIOBE programming exponential curve
Draw TIOBE programming exponential curve
describe
The TIOBE Programming Community Index is an indicator of the popularity of programming languages. The index is updated monthly. Ratings are based on the number of skilled engineers, courses and third-party vendors worldwide. Popular search engines such as Google, Bing, Yahoo, Wikipedia, Amazon, YouTube, and Baidu are used for index calculations.
It should be noted that the TIOBE index does not represent the quality of the language, the index can be used to check whether the developer's programming skills are still up-to-date, or to make a strategic decision about which programming language should be used when starting to build a new software system. decision making.
Visit the website: https://www.tiobe.com/tiobe-index/, you can see the programming language index curve in December 2021 as follows:
The data of this curve is hidden in the webpage, extract the data from the webpage and save it in the attached text, read the data in the text, and use matplotlib to draw the graph in the example:
Example 1 is a line graph, which requires the line width to be 2, the curve thickness of the Python language to be 4, and the label to be placed at an appropriate position.
Example 2 is a pie chart, drawing requires a reference illustration, and the data is the ranking data of the last month.
matplotlib.pyplot.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=0, radius=1, counterclock=True, wedgeprops=None, textprops=None, center=(0, 0), frame=False, rotatelabels=False, *, normalize=True, data=None)
Requirements: Submit the code that can run, and upload the screenshot of the drawing result as an attachment.
Input and output example
import numpy
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
#**********读取数据**********
class Date:
def UTC(obj,year,month,day):
date=[str(year),str(month),str(day)]
return '-'.join(date)
with open('tiobe202112.txt','r') as f:
name,data,Date='name','data',Date()
res=eval(f.read())
print(res)
#**********绘制折线图**********
_data={}
for i in res:
_data[i['name']]=i['data']
_x=['2002','2004','2006','2008','2010',
'2012','2014','2016','2018','2020']
fig = plt.figure(figsize=(30, 20), dpi=100)
for i in _data.keys():
x=[x[0] for x in _data[i]]
y=[y[1] for y in _data[i]]
plt.plot(x,y,lw=4)
plt.legend(_data.keys(), ncol=2)
plt.xticks([x[0] for x in _data['Python'] if x[0][0:4] in _x][::12],labels=_x)
plt.savefig('_data.png')
plt.show()
#**********绘制饼图**********
_data_=[i['data'][-1][1] for i in res]
plt.pie(_data_,labels=_data.keys(),autopct='%.2f%%')
plt.legend(_data.keys(),loc=2,bbox_to_anchor=(1.05,1.0),borderaxespad=0.)
plt.savefig('_data_.png')
plt.show()
Data processing in this question
JSON data:
[{"firstName":"John","lastName":"Doe" },
{"firstName":"Anna","lastName":"Smith" },
{"firstName":"Peter","lastName":"Jones" }]
Data for this question:
[{name:'Python',data:[[Date.UTC(2001, 5, 30), 1.25],[Date.UTC(2001, 6, 30), 1.13],...]},
{name:'C',data:[[Date.UTC(2001, 5, 30), 20.24],[Date.UTC(2001, 6, 30), 20.77],...]},
...]
Both the JSON data and the data structure of this question are key-value pairs, but the key of the former is a string, while the key in the data of this question is not a string, and the value also includes the Date object of JS (for example, Date.UTC(2001 , 5, 30)). To sum up, the data in this question obviously cannot be read using the JSON library, and if you use eval() on it, the following problems will occur:
with open('tiobe202112.txt','r') as f:
res=eval(f.read())
The error message in the figure shows that eval() recognizes the name (key) in the data as a variable. Modify the code, try to define name, data, the result is as follows:
with open('tiobe202112.txt','r') as f:
name,data='name','data'
res=eval(f.read())
The error message in the figure shows that eval() cannot recognize the UTC method of the JS Date object. Similarly, modify the code again, try to define the Date object and create the method UTC inside it, the result is successfully read
class Date:
def UTC(obj,year,month,day):
date=[str(year),str(month),str(day)]
return '-'.join(date)
with open('tiobe202112.txt','r') as f:
name,data,Date='name','data',Date()
res=eval(f.read())
Object Orientation in Python
Reference article: https://zhuanlan.zhihu.com/p/30024792
exercise
1. Dynamically draw a Cartesian heart-shaped line.
The following code is ported, it is recommended to read the blog of the original blogger
Portal: https://blog.csdn.net/qq_42951560/article/details/118519398
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
figure = plt.figure()
line1, = plt.axes(xlim=(-1.5, 1.5), ylim=(-2.2, 0.45)).plot([], [], c='r')
line2, = plt.axes(xlim=(-1.5, 1.5), ylim=(-2.2, 0.45)).plot([], [], c='r')
def init():
line1.set_data([], [])
line2.set_data([], [])
return line1, line2
def update(i, a):
theta = np.linspace(0, i/np.pi, 100)
x = a*(1-np.cos(theta))*np.sin(theta)
y = a*(1-np.cos(theta))*np.cos(theta)
line1.set_data(x, y)
line2.set_data(-x, y)
return line1, line2
def cardioid_animate(a):
ani = animation.FuncAnimation(figure, update, init_func=init, frames=11, fargs=(a,), blit=True)
plt.axis('off')
ani.save('./img.gif')
plt.show()
if __name__ == '__main__':
cardioid_animate(1)
Animations in the matplotlib library
animation.FuncAnimation(figure, update, init_func, frames, fargs, blit)
fig: Set the canvas for drawing animation
func: Set the frame function, call the function every frame
frames: Define the number of animation frames
init_func: Set the initialization function, used for animation initial frame
fargs: Optional arguments, which can be a tuple or None, are additional arguments passed to each invocation of func
blit: choose to update all points, or only update points that have changed. Usually it is True (for mac users, please select False, otherwise it cannot be displayed)
Reference blog: https://blog.csdn.net/miracleoa/article/details/115407901
Reference article: https://vimsky.com/examples/usage/matplotlib-animation-funcanimation-class-in-python.html
2. King of Glory has 5 corresponding position occupations: top laner, mid laner, jungler, support, and AD. The authority scores each occupation on a scale of 0-16. Play 10 rounds of games for the above five different occupations, score randomly, and record their average scores. Finally, a radar chart of the distribution of these five occupational ratings is drawn.
# coding=utf-8
import random
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"]="SimHei"
plt.rcParams["axes.unicode_minus"]=False
pi=np.pi
occs=['上单','中单','打野','辅助','AD']
occ=np.concatenate((occs,[occs[0]]))
thetas=[0,0.4,0.8,1.2,1.6]
theta=np.concatenate((thetas,[thetas[0]]))
def game():
res={}
for i in occs:
res[i]=random.randint(0,16)
return res
if __name__=='__main__':
res=[i for i in game().values()]
r=np.concatenate((res,[res[0]]))
print(r)
fig = plt.figure(figsize=(6, 6), dpi=100)
ax=plt.subplot(111, polar=True)
ax.set_theta_zero_location('N') #设置极轴方向
ax.set_thetagrids(theta*180,occ) #设置标签
ax.set_rlabel_position(0.2*180) #设置刻度位置
ax.plot(theta*pi,r,'ro-',lw=2) #填充颜色
ax.fill(theta*pi,r,facecolor='r',alpha=0.2)
ax.set_rlim(0,16) #设置极轴区间
plt.savefig('./_img.png')
plt.show()
concatenate() in the numpy library
for concatenating multiple arrays
import numpy as np
a=np.array([1,2,3])
b=np.array([4,5,6])
c=np.concatenate((a,b))
#[1,2,3,4,5,6]
a=np.array([[1,2,3],[4,5,6]])
b=np.array([[7,8,9],[10,11,12]])
np.concatenate((a,b),axis=0) #axis=0按列拼接
'''
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
'''
np.concatenate((a,b),axis=1) #axis=0按行拼接
'''
[[ 1 2 3 7 8 9]
[ 4 5 6 10 11 12]]
'''
Reference blog: https://blog.csdn.net/qq_30638831/article/details/79938841