'How can I fix a ValueError in a matplotlib code?
import matplotlib.pyplot as plt
import numpy as np
import time
class Data:
def setdata(self, label, color, datalist):
self.label = label
self.color = color
self.datalist = datalist
week = 8
base = Data()
d1 = d2 = d3 = d4 = d5 = d6 = d7 = d8 = Data()
base.setdata('a', 'tomato', [])
d1.setdata('b', 'red', [2, 3, 4, 6, 7, 8, 2, 6])
d2.setdata('c', 'cyan', [7, 12, 23, 27, 45, 68, 78, 99])
d3.setdata('d', 'deepskyblue', [7, 12, 23, 27, 45, 68, 78, 99])
d4.setdata('e', 'steelblue', [7, 12, 23, 27, 45, 68, 78, 99])
d5.setdata('f', 'limegreen', [7, 12, 23, 27, 45, 68, 78, 99])
d6.setdata('g', 'yellow', [7, 12, 23, 27, 45, 68, 78, 99])
d7.setdata('h', 'mediumblue', [7, 12, 23, 27, 45, 68, 78, 99])
d8.setdata('i', 'orangered', [7, 12, 23, 27, 45, 68, 78, 99])
datadict = {1: d1, 2: d2, 3: d3, 4: d4, 5: d5, 6: d6, 7: d7, 8: d8}
print('wanted key: ')
key = int(input())
data = datadict[key]
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
for num in range(1, week):
x = np.arange(0, num, 1)
ax1.plot(x, data.datalist[0:num], color=data.color)
ax2.plot(x, base.datalist[0:num], color=base.color)
plt.show()
time.sleep(2)
Need some help on this code. I see a error like this: ValueError: x and y must have same first dimension, but have shapes (1,) and (0,), and it is pretty annoying because the first dimension of y goes (2,) when I change the slicing index to [0:num+1] in the for-loop.
P.S. If there's a hidden error on another side of the code, let me know. Would be very thankful for the help.
Solution 1:[1]
Here is a version that works. Perhaps this can give you a starting point.
import matplotlib.pyplot as plt
import numpy as np
import time
class Data:
def __init__(self, label, color, datalist):
self.label = label
self.color = color
self.datalist = datalist
week = 8
base = Data('a', 'tomato', [2, 2, 2, 2, 2, 2, 2, 2, 2])
d1 = Data('b', 'red', [2, 3, 4, 6, 7, 8, 2, 6])
d2 = Data('c', 'cyan', [7, 12, 23, 27, 45, 68, 78, 99])
d3 = Data('d', 'deepskyblue', [7, 12, 23, 27, 45, 68, 78, 99])
d4 = Data('e', 'steelblue', [7, 12, 23, 27, 45, 68, 78, 99])
d5 = Data('f', 'limegreen', [7, 12, 23, 27, 45, 68, 78, 99])
d6 = Data('g', 'yellow', [7, 12, 23, 27, 45, 68, 78, 99])
d7 = Data('h', 'mediumblue', [7, 12, 23, 27, 45, 68, 78, 99])
d8 = Data('i', 'orangered', [7, 12, 23, 27, 45, 68, 78, 99])
datadict = {1: d1, 2: d2, 3: d3, 4: d4, 5: d5, 6: d6, 7: d7, 8: d8}
print('wanted key: ')
key = int(input())
data = datadict[key]
#fig, ax1 = plt.subplots()
#ax2 = ax1.twinx()
x = list(range(8))
for num in range(2, week):
plt.plot(x[:num], data.datalist[:num], color=data.color)
plt.plot(x[:num], base.datalist[:num], color=base.color)
plt.show()
# time.sleep(2)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tim Roberts |
