向整数X轴添加字符串

2024-04-25 05:42:53 发布

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

我在x轴(溶液浓度)和效率(y)之间画一张图。我将此设置为在0到100之间显示x,但我想添加另一个数据点作为控件,而不需要任何解决方案。我有问题,因为这并不真正适合任何地方的浓度轴,但我想添加它要么在0之前或100之后,有可能在轴中断分离他们。所以我的x轴看起来像['control',0,20,40,60,80,100]

中全景:

x_array = ['control', 0, 20, 40, 50, 100]
y_array = [1, 2, 3, 4, 5, 6]
plt.plot(x_array, y_array)

尝试这个,我得到一个错误:

ValueError: could not convert string to float: 'control'

你知道我怎么能做这样的事吗?我看了xticks,但是它会把x轴绘制成字符串,因此失去了轴的连续性,这会把绘图搞砸,因为数据点的间距不是相等的。你知道吗


Tags: 数据plot地方错误plt解决方案arraycontrol
1条回答
网友
1楼 · 发布于 2024-04-25 05:42:53

可以将单个点作为对plot的单独调用添加到图形中,然后调整x轴标签。你知道吗

import matplotlib.pyplot as plt

x_array = [0, 20, 40, 50, 100]
y_array = [2, 3, 4, 5, 6]
x_con = -20
y_con = 1
x_ticks = [-20, 0, 20, 40, 60, 80, 100]
x_labels = ['control', 0, 20, 40, 60, 80, 100]

fig, ax = plt.subplots(1,1)
ax.plot(x_array, y_array)
ax.plot(x_con, y_con, 'ro')  # add a single red dot

# set tick positions, adjust label text
ax.xaxis.set_ticks(x_ticks)
ax.xaxis.set_ticklabels(x_labels)
ax.set_xlim(x_con-10, max(x_array)+3)
ax.set_ylim(0,7)
plt.show()

enter image description here

相关问题 更多 >