Matplotlib:如何仅为抽搐设置最小值和最大值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Matplotlib:如何仅为抽搐设置最小值和最大值相关的知识,希望对你有一定的参考价值。
我有类似的代码来绘制:
plt.plot(df_tags[df_tags.detailed_tag == tag]['week'], df_tags[df_tags.detailed_tag == tag].tonality)
但我希望这样只留下x轴的最小值和最大值:
plt.plot(df_tags[df_tags.detailed_tag == tag]['week'], df_tags[df_tags.detailed_tag == tag].tonality)
plt.xticks([df_tags['week'].min(), df_tags['week'].max()])
print (df_tags['week'].min(), df_tags['week'].max())
答案
由于未知的输入数据,无法确定地回答这个问题。解释显示的少量代码,用于设置刻度和标签,
t = [df_tags['week'].min(), df_tags['week'].max()]
plt.xticks(t,t)
To explain why
plt.xticks(t)
alone does not work:The inital plot's axis has some tick locations and ticklabels set, i.e. tick locations corresponding to
[2018-03, 2018-04, 2018-05,...]
and the respective ticklabels [2018-03, 2018-04, 2018-05,...]
. If you now only change the tick locations via plt.xticks([2018-03, 2018-08])
, the plot will only have two differing tick locations, but still the same labels to occupy those locations. Hence the second label 2018-04
will occupy the second (and last) position.Since this is undesired, you should always set the tick positions and the ticklabels. This is done via
plt.xticks(ticklocations, ticklabels)
or ax.set_xticks(ticklocations); ax.set_xticklabels(ticklabels)
.
另一答案
这个hacky解决方案搭载在这个SO post上
import pandas as pd
import numpy as np
df = pd.DataFrame({'week': ['2018-01', '2018-02', '2018-03', '2018-04', '2018-05', '2018-06', '2018-07', '2018-08'], 'val': np.arange(8)})
fig, ax = plt.subplots(1,1)
ax.plot(df['week'], df['val'])
for i, label in enumerate(ax.get_xticklabels()):
if i > 0 and i < len(ax.get_xticklabels()) - 1:
label.set_visible(False)
plt.show()
以上是关于Matplotlib:如何仅为抽搐设置最小值和最大值的主要内容,如果未能解决你的问题,请参考以下文章