python plotting custom x-axis

t_range = pd.date_range('2020-01-01', '2021-1-1', freq='10min', closed='left')
t_range_test = t_range.map(lambda x: x.strftime('%m-%d %H:%M:%S'))

Output view effect:

t_range_test
Out[42]: 
Index(['01-01 00:00:00', '01-01 00:10:00', '01-01 00:20:00', '01-01 00:30:00',
       '01-01 00:40:00', '01-01 00:50:00', '01-01 01:00:00', '01-01 01:10:00',
       '01-01 01:20:00', '01-01 01:30:00',
       ...
       '12-31 22:20:00', '12-31 22:30:00', '12-31 22:40:00', '12-31 22:50:00',
       '12-31 23:00:00', '12-31 23:10:00', '12-31 23:20:00', '12-31 23:30:00',
       '12-31 23:40:00', '12-31 23:50:00'],
      dtype='object', length=52704)

Matching failure: The topmost value close to 14 is originally a continuous date, but because other items also have this date, and the date is earlier than it, there will be such a segmented situation.
insert image description here
Draw labels to see why continuous data is displayed in segments.

fig = plt.figure(figsize=(16, 8))
plt.scatter(data_ws_draw['test'], data_ws_draw['percentage'])
plt.xticks(range(0, len(data_ws_draw['test']), 4320), rotation=45)
for i, txt in enumerate(data_ws_draw['test']):
    if i%400==0:  # 标签也可以通过 rotation 进行旋转
	    plt.annotate(txt, (data_ws_draw['test'][i],data_ws_draw['percentage'][i]), rotation=90)  

Case 1

insert image description here

plt.xticks(range(160000,320000,20000), labels=[‘160K’, ‘180K’, ‘200K’, ‘220K’, ‘240K’, ‘260K’, ‘280K’, ‘300K’])

insert image description here

Case 2

insert image description here
How to make the x-axis displayed every 20 points? Focus on the 6th last line of code.

import json
from matplotlib import pyplot as plt
 
filename='btc_close_2017.json'
with open(filename) as f:
    btc_data=json.load(f)
    
#创建5个列表,存储日期和收盘价
dates=[]
months=[]
weeks=[]
weekdays=[]
close=[]
 
#打印每一天的信息
for btc_dict in btc_data:
    dates.append(btc_dict['date'])
    months.append(int(btc_dict['month']))
    weeks.append(int(btc_dict['week']))
    weekdays.append(btc_dict['weekday'])
    close.append(int(float(btc_dict['close'])))
  
#创建图表
fig=plt.figure(dpi=128,figsize=(10,6))    
plt.plot(dates,close,c='blue')
 
#设置图标格式
plt.rcParams['font.sans-serif']=['SimHei'] #指定默认字体
plt.rcParams['axes.unicode_minus']=False  #解决保存图像时符号-显示为方块的2问题
 
plt.title("收盘价 (RMB)",fontsize=20)
#plt.xlabel=('')
plt.xticks(range(0,365,20)) #共365个值,每20个点显示一次
fig.autofmt_xdate()
#plt.ylabel('', fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=16)
 
plt.show()

insert image description here

Case 3

# xax = p1.getAxis('left') # 改成坐标轴y
xax = p1.getAxis('bottom') # 坐标轴x
ticks = [list(zip(range(10), ('16:23', '16:28', '16:33', '16:40', '16:45','16:23', '16:28', '16:33', '16:40', '16:45')))] # 声明五个坐标,分别是
xax.setTicks(ticks)

insert image description here

Case 4

Drawing must have data, both x and y must have data, otherwise graphics cannot be generated. Here is to change the label of the x-axis to the required string label. All the strings are read back from the entry. You can use int()/ or ong() to convert the read results into numbers. If the input is not a number, TypeError will be raised.

x=1:5;
y=3*rand(1,5);
plot(x,y)
set(gca,'xtick',[1 2 3 4 5])
set(gca,'xticklabel',{
    
    'a','b','c','d','e'})

scatter scatter plot display label

import numpy as np
import matplotlib.pyplot as plt
 
x = [2.3,4.5,3,7,6.5,4,5.3]
y = [5,4,7,5,5.3,5.5,6.2]
n = np.arange(7)
 
fig, ax = plt.subplots()
ax.scatter(x, y, c='r')
 
for i, txt in enumerate(n):
	ax.annotate(txt, (x[i],y[i]))

When clustering, we need to see the distribution of the data, and to observe the data more intuitively, we can use this. When encountering Chinese garbled characters, you can use the following code:

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

References

[1] Python matplotlib plt draws the x-axis or y-axis coordinates, and replaces the scale with text/characters 2021.1;
[2] When python uses matplotlib to draw, the x-axis is the time axis, how to make the x-axis display every few points ? 2020.11;
[3] ticks_and_spines example code: tick_labels_from_values.py 2017.5;

Guess you like

Origin blog.csdn.net/weixin_46713695/article/details/130226154