首页 > 解决方案 > 如何以相同的距离减少matplot中的y轴

问题描述

我希望这个图的 y 轴以 38 为中心,并且 y 轴缩放以使“驼峰”消失。我该如何做到这一点?

在此处输入图像描述

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
s=['05/02/2019', '06/02/2019', '07/02/2019', '08/02/2019', 
   '09/02/2019', '10/02/2019', '11/02/2019', '12/02/2019', 
   '13/02/2019', '20/02/2019', '21/02/2019', '22/02/2019', 
   '23/02/2019', '24/02/2019', '25/02/2019']
df[0]=['38.02', '33.79', '34.73', '36.47', '35.03', '33.45',
       '33.82', '33.38', '34.68', '36.93', '33.44', '33.55', 
       '33.18', '33.07', '33.17']
# Data for plotting
fig, ax = plt.subplots(figsize=(17, 2))
for i,j in zip(s,df[0]):
    ax.annotate(str(j),xy=(i,j+0.8))
ax.plot(s, df[0])
ax.set(xlabel='Dates', ylabel='Latency',
       title='Hongkong to sing')
ax.grid()
#plt.yticks(np.arange(min(df[p]), max(df[p])+1, 2))
fig.savefig("test.png")
plt.show()

标签: pythonmatplotlib

解决方案


我不完全确定这是否是您正在寻找的,但您可以明确调整 y 限制以更改比例,即

ax.set_ylim([ax.get_ylim()[0], 42])

只设置上限,保持下限不变,这会给你 Y轴限位控制(上)

您可以提供您认为合适的任何值,即

ax.set_ylim([22, 52])

会给你一些看起来像的东西 Y轴限位控制(两者)

另请注意,您的绘图的刻度标签和总体外观将与此处显示的不同。


编辑- 这是所要求的完整代码:

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df = pd.DataFrame()
s=['05/02/2019', '06/02/2019', '07/02/2019', '08/02/2019', 
   '09/02/2019', '10/02/2019', '11/02/2019', '12/02/2019', 
   '13/02/2019', '20/02/2019', '21/02/2019', '22/02/2019', 
   '23/02/2019', '24/02/2019', '25/02/2019']
df[0]=['38.02','33.79','34.73','36.47','35.03','33.45',
       '33.82','33.38','34.68','36.93','33.44','33.55',
       '33.18','33.07','33.17']
# Data for plotting
fig, ax = plt.subplots(figsize=(17, 3))
#for i,j in zip(s,df[0]):
#    ax.annotate(str(j),xy=(i,j+0.8))

ax.plot(s, pd.to_numeric(df[0]))
ax.set(xlabel='Dates', ylabel='Latency',
       title='Hongkong to sing')
ax.set_xticklabels(pd.to_datetime(s).strftime('%m.%d'), rotation=45)
ax.set_ylim([22, 52])
plt.show()

推荐阅读