matplotlib - 如何以不规则的2^n间隔绘制图形?

2024-10-08 21:13:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有2个列表,每个列表有128个元素

x = [1,2,3,...,128]
y = [y1,y2,...,y128]

我应该如何使用matplotlib来绘制(x,y),其中x轴如screenshot所示?在

为了复制图表,我已经(1)从原始列表中创建了2个附加列表,并且(2)使用了set-xticklabels:

^{pr2}$

这种方法的问题是只绘制了8对值,而省略了120对。在


Tags: 方法元素列表matplotlib图表绘制省略screenshot
2条回答

你要找的是一个以2为底的对数刻度。matplotlib提供对数标度,您可以定义任意基数:

from matplotlib import pyplot as plt
from matplotlib.ticker import ScalarFormatter
#sample data
x = list(range(1, 130))
y = list(range(3, 260, 2)) 

f, ax1 = plt.subplots(1,1,figsize=(16,7))
x1 = [  1,   2,   4,   8,   16,   32,   64,   128]
y1 = [y[0],y[1],y[3],y[7],y[15],y[31],y[63],y[127]]
#just the points, where the ticks are
ax1.plot(x1, y1,"bo-", label = "Performance")
#all other points to contrast this
ax1.plot(x, [270 - i for i in y], "rx-", label = "anti-Performance")
#transform x axis into logarithmic scale with base 2
plt.xscale("log", basex = 2)
#modify x axis ticks from exponential representation to float 
ax1.get_xaxis().set_major_formatter(ScalarFormatter())
ax1.set_xlabel('Time Period',fontsize=15)
ax1.set_ylabel("Value",color='b',fontsize=15)
plt.legend()
plt.show()

输出:

enter image description here

如果我的意见不够清楚,请你问。:)

from matplotlib import pyplot as plt

#   Instanciating my lists...
f = lambda x:x**2
x = [nb for nb in range(1, 129)]
y = [f(nb) for nb in x]

#   New values you want to plot, with linear spacing.
indexes_to_keep = [1, 2, 4, 8, 16, 32, 64, 128]
y_to_use = [y[nb - 1] for nb in indexes_to_keep]

#   First plot that shows the 128 points as a whole.
fig = plt.figure(figsize=(10, 5.4))
ax1 = fig.add_subplot(121)
ax1.plot(x, y)
ax1.set_title('Former values')

#   Second plot that shows only the indexes you wish to keep.
ax2 = fig.add_subplot(122)

#   my_ticks = [1, 2, 3, 4, 5, 6, 7]
#   meaning : my_ticks will be linear values.
my_ticks = [i for i in range(len(indexes_to_keep))]

#   We set the ticks we want to show, meaning : all our list
#   instead of some linear spacing matplotlib will show by default
ax2.set_xticks(my_ticks)

#   Then, we manually change the name of the X ticks.
ax2.set_xticklabels(indexes_to_keep)

#   We will then, plot the LINEAR x axis,
#   but with respect to the y-axis values pre-processed.
ax2.plot(my_ticks, y_to_use)
ax2.set_title('New selected values with linear spacing')

plt.show()

正在显示。。。在

Imgur

相关问题 更多 >

    热门问题