Python – Plot the y-axis using a string appended to each value

Plot the y-axis using a string appended to each value… here is a solution to the problem.

Plot the y-axis using a string appended to each value

I plot the chart with the following code:

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

The values that appear on the y-axis are values from list1 and list2.

I’m trying to get my y-axis to start with the variable v so that the y-axis reads the values in “v+” list1 and list2.
So basically instead of starting from zero, I want the y-axis to start at “v” followed by the “v+” value in the list.

Is this possible because I plotted two different lists on the same graph?

I tried :

I tried changing y_ticks:: before calling the plot function

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()  

This results in valueError: Unable to convert string to float.

Solution

You ask matplotlib to plot the string “v + 10" in the chart. It’s like asking where “abracadabra” is on the number line – it’s impossible. That is, you need to go back to the initial code and draw the list yourself. As for the ticks, you can set them

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

Full example:

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

A different, more generic option is to use a formatter for the y-axis, which includes "v+".

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

Full example:

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()  

The output is basically the same as above, but it doesn’t depend on how many entries the list has, or whether they are interleaved.

Related Problems and Solutions