开发者

Plotting values versus strings in matplotlib?

开发者 https://www.devze.com 2023-03-29 01:48 出处:网络
I am trying to create a plot in matplotlib where the x-values are integers and the y-values are strings. Is it possible to plot data of this type in matplotlib? I examined the documentation and the ga

I am trying to create a plot in matplotlib where the x-values are integers and the y-values are strings. Is it possible to plot data of this type in matplotlib? I examined the documentation and the gallery for matplotlib and could not find any examples of this type.

I have many lists bound to a variable called my_lists. The structure looks like this:

mylists = [765340, 765371, 765310,'MA011',],
          [65310, 'MA015'],
          [765422, 765422, 24920205, 24920161, 'MA125'],
          [765422, 'MA105'], 
          [765371, 12345, 'MA004']

In each list, all items except the last item are x-values. The last item in each list is a string, which is the single y-value. How can I plot this is matplotlib? Here was my attempt:

import matplotlib.pyplot as plt

for sub_list in my_lists:
    x_value = sub_list[:1]
    y_value = sub_list[-开发者_Python百科1]
    plt.plot(x_value, y_value, "ro")
    plt.show()

The above code throws me this error:

ValueError: could not convert string to float: MA011

How can integers versus strings be plotted?


You could probably do something like this, where you give each y "string" a unique index value. You may have to fiddle with the spacing for i. Ie. i*2 instead of i to make things look nice. After that you set the tick label for each of those indexes to its corresponding string.

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(9,7))
ax1 = fig.add_subplot(111)


mylists = [[765340, 765371, 765310,'MA011',], [65310, 'MA015'], 
           [765422, 765422, 24920205, 24920161, 'MA125'],
           [765422, 'MA105'],[765371, 12345, 'MA004']]

x = []
y = []
y_labels = []
y_ticks = []
for i,sub_list in enumerate(mylists):
    y_labels.append(sub_list[-1])
    y_ticks.append(i)
    for v in sub_list[:-1]:
        x.append(v)
        y.append(i)

ax1.set_yticks(y_ticks)
ax1.set_yticklabels(y_labels)
ax1.plot(x, y, "ro")
plt.show()

EDIT:

Sorry I forgot to include the enuemrate call in the for loop. It basically sets the value of i to the index of the current sub_list. Then you use the index instead of the string value as the y-value. After that you replace the label for those y-values with the actual string value.

0

精彩评论

暂无评论...
验证码 换一张
取 消