2017-09-15 43 views
0
from matplotlib.lines import Line2D 
import numpy as np 

fig = plt.figure(figsize=(6,6)) 

plt.plot([1, 2, 4, 8, 12, 16, 20, 24], color='black', marker=None) 

labels = ['1', '2', '4', '8', '12', '16', '20', '24'] 
xticks = [1,2,3,4,5,6,7,8] 
nthreads = [1,2,4,8,12,16,20,24] 

plt.xticks(xticks, labels) 
plt.yticks(nthreads, labels) 

plt.show() 

我试图产生f(x)= x的图,但我无法摆脱行中的弯曲。还有一个X轴刻度标签的右移。Matplotlib xtick ytick

如何通过点(1,1),(2,2),...,(24,24)绘制直线并固定x轴标签移位?

Plot generated by the code above

我试过的nthreadsxticks其他所有排列为plt.xticks()plt.yticks(),分别,没有结果的期待接近我想要的东西。

回答

2

当您没有设置x数组matplotlib时,使用默认列表[0,1,2,3,4,5,6,7]。因此你不会得到一条直线。您必须指定阵列xy。在你的情况下,他们必须是相同的。

如果您想放置标签,请使用此示例中的位置和标签。移动当前轴(plt.gca())的坐标系集xlimylim

from matplotlib.lines import Line2D 
import matplotlib.pyplot as plt 
import numpy as np 
# plot y=x 
fig = plt.figure(figsize=(6,6)) 
x = [1, 2, 4, 8, 12, 16, 20, 24] 
plt.plot(x,x, color='black', marker=None) 
# put labels for all ticks 
labels = np.arange(1,25,1) 
plt.xticks(labels, labels) 
plt.yticks(labels, labels) 
# set limits of axis 
ax = plt.gca() 
ax.set_xlim([1,24]) 
ax.set_ylim([1,24]) 

plt.show() 

enter image description here