如何解决想要在使用 matplotlib.pyplot 时部分删除 x 轴上的项目
我正在设计一个货币转换器应用程序,我有一个想法,可以为它添加图形货币分析。 为此,我已经开始使用 matplotlib.pyplot 。我从用户输入日期(即图表比较数据的日期)作为输入。使用这些数据,我从某些来源获取实时货币数据。 但主要问题来了。当我画图时,x 轴真的很糟糕?。 我将插入我得到的输出--> 图形和我的粗略代码。我想消除的主要问题是我只希望 x 轴的某些部分可见。
import matplotlib.pyplot as plt
import requests
x = []
y = []
for i in range(fyear,tyear):
for j in range(fmonth,tmonth):
for k in range(fday,tday):
response = requests.get("https://api.ratesapi.io/api/{}-{}-{}?base={}&symbols{}".format(i,j,k,inp_curr,out_curr))
data = response.json()
rate = data['rates'][out_curr]
y.append(rate)
x.append("{}/{}/{}".format(j,i,k))
plt.plot(x,y)
获得的输出: enter image description here 急需答复.....
解决方法
如果对于零件,您只想沿 x 轴设置几个标签,则可以使用 xticks 和 locator_params。请参阅此处的文档:https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.xticks.html
import matplotlib.pyplot as plt
import numpy as np
import requests
# use some fake data for testing - use your params
fyear = 2019
tyear = 2020
fmonth = 1
tmonth = 13
fday=1
tday=28
inp_curr = "EUR"
out_curr = "GBP"
# init lists
x = []
y = []
for i in range(fyear,tyear):
for j in range(fmonth,tmonth):
for k in range(fday,tday):
response = requests.get("https://api.ratesapi.io/api/{}-{}-{}?base={}&symbols{}".format(i,j,k,inp_curr,out_curr))
data = response.json()
rate = data['rates'][out_curr]
y.append(rate)
x.append("{}/{}/{}".format(j,i,k))
# create subplot
fig,ax = plt.subplots(1,1,figsize=(20,11))
# plot image
img = ax.plot(x,y)
# set the total number of x_ticks (the ticks on the x label)
ax.set_xticks(np.arange(len(x)))
# set the labels for each x_tick (actually is x list)
ax.set_xticklabels(x)
# set the number of ticks you want to visualize
# you can just select a number i.e. 10 and you will visualize onlu 10 ticks
# in order to visualize,say the first day of each month set this
n = round(len(x)/(tday-fday))
plt.locator_params(axis='x',nbins=n)
# change labels position to oblique
ax.get_figure().autofmt_xdate()
fig.tight_layout()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。