python - 使用附加到每个值的字符串绘制 y 轴

标签 python matplotlib yaxis

我使用以下代码绘制图表:

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(t_list,list1,linestyle='-')
ax.plot(t_list,list2,linestyle='--')
plt.show()  

出现在 y 轴上的值是来自 list1 和 list2 的值。

我试图让我的 y 轴从变量 v 开始,以便 y 轴读取“v +”list1 和 list2 中的值。 所以基本上不是从零开始,我希望 y 轴从“v”开始,然后是列表中的“v +”值。

这可能吗,因为我在同一张图上绘制了两个不同的列表?

我尝试过的:

我尝试在调用绘图函数之前更改 y_ticks:

fig = plt.figure()
ax = fig.add_subplot(111)
y_ticks1 = ["v + " + str(y) for y in list1]
y_ticks2 = ["v + " + str(y) for y in list2]
ax.plot(t_list,y_ticks1,linestyle='-')
ax.plot(t_list,y_ticks2,linestyle='--')
plt.show()  

这会导致 valueError:无法将字符串转换为 float 。

最佳答案

您要求 matplotlib 在图表中绘制字符串 "v + 10"。这就像问“abracadabra”在数轴上的位置 - 这是不可能的。也就是说,您需要返回到初始代码并自行绘制列表。至于滴答声,你可以设置它们

ax.set_yticks(list1+list2)
ax.set_yticklabels([ "v + " + str(y) for y in list1+list2])

完整示例:

import matplotlib.pyplot as plt

t_list = [1,2,3]
list1 = [1,2,3]
list2 = [4,5,6]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(t_list,list1,linestyle='-')
ax.plot(t_list,list2,linestyle='--')

ax.set_yticks(list1+list2)
ax.set_yticklabels([ "v + " + str(y) for y in list1+list2])
plt.show() 

enter image description here

一个不同的、更通用的选项是为 y 轴使用格式化程序,其中包括 "v + "

ax.yaxis.set_major_formatter(StrMethodFormatter("v + {x}"))

完整示例:

import matplotlib.pyplot as plt
from matplotlib.ticker import StrMethodFormatter

t_list = [1,2,3]
list1 = [1,2,3]
list2 = [4,5,6]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(t_list,list1,linestyle='-')
ax.plot(t_list,list2,linestyle='--')

ax.yaxis.set_major_formatter(StrMethodFormatter("v + {x}"))

plt.show()  

输出与上面基本相同,但它不取决于列表有多少条目,或者它们是否交错。

关于python - 使用附加到每个值的字符串绘制 y 轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46516465/

相关文章:

datetime - Python 绘图时间

python - 用 matplotlib 画圆圈,边框不在图中

flutter - 是否可以在 Flutter 图表上缩放垂直轴?

JavaFX独立旋转NumberAxis

python - Discord Bot 返回 "HTTPException: BAD REQUEST (status code: 400): Cannot send an empty message"尽管我发送的是非空消息

python - 为什么 Python 3 的常规字符串替换会吞掉字符?

python - Django - 将命令传递给 shell

python - 一定数量的字符后标准输出循环停止

python - 如何制作这种条形图,将列表交易分为 12 组条形图?

r - ggplot2 facet_grid 在 y 轴上创建面板