I am trying to create a colored line with certain conditions. Basically I would like to have the line colored red when pointing down on the y axis, green when pointing up and blue when neither.
I played around with some similar examples I found but I have never been able to convert them to work with plot() on an axis. Just wondering how this could be done.
Here is some code that I have come up with so far:
CREATE TABLE `sessions` (
`id` int(128) NOT NULL AUTO_INCREMENT,
`ip` varchar(128) COLLATE latin1_general_ci NOT NULL,
`hostname` varchar(128) COLLATE latin1_general_ci NOT NULL,
`city` varchar(128) COLLATE latin1_general_ci NOT NULL,
`region` varchar(128) COLLATE latin1_general_ci NOT NULL,
`country` varchar(128) COLLATE latin1_general_ci NOT NULL,
`loc` varchar(128) COLLATE latin1_general_ci NOT NULL,
`org` varchar(128) COLLATE latin1_general_ci NOT NULL,
`postal` varchar(128) COLLATE latin1_general_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1 ;
Not sure how to get plot() to accept an array of colors. I always get an error about the format type used as the color. Tried heximal, decimal, string and float. Works perfect with scatter().
Thanks
答案 0 :(得分:2)
我认为你不能在plot
中使用颜色数组(文档说颜色可以是任何matlab颜色,而scatter
文档说你可以使用数组)。
但是,你可以通过分别绘制每一行来伪造它:
import numpy
from matplotlib import pyplot as plt
x = range(10)
y = numpy.random.choice(10,10)
for x1, x2, y1,y2 in zip(x, x[1:], y, y[1:]):
if y1 > y2:
plt.plot([x1, x2], [y1, y2], 'r')
elif y1 < y2:
plt.plot([x1, x2], [y1, y2], 'g')
else:
plt.plot([x1, x2], [y1, y2], 'b')
plt.show()
答案 1 :(得分:2)
行。所以我想出了如何使用LineCollecion在轴上绘制线条。
import numpy as np
import pylab as pl
from matplotlib import collections as mc
segments = []
colors = np.zeros(shape=(10,4))
x = range(10)
y = np.random.choice(10,10)
i = 0
for x1, x2, y1,y2 in zip(x, x[1:], y, y[1:]):
if y1 > y2:
colors[i] = tuple([1,0,0,1])
elif y1 < y2:
colors[i] = tuple([0,1,0,1])
else:
colors[i] = tuple([0,0,1,1])
segments.append([(x1, y1), (x2, y2)])
i += 1
lc = mc.LineCollection(segments, colors=colors, linewidths=2)
fig, ax = pl.subplots()
ax.add_collection(lc)
ax.autoscale()
ax.margins(0.1)
pl.show()
答案 2 :(得分:0)
有example on the matplotlib page显示如何使用LineCollection
绘制多色线条。
剩下的问题是获取行集合的颜色。因此,如果y
是要比较的值,
cm = dict(zip(range(-1,2,1),list("gbr")))
colors = list( map( cm.get , np.sign(np.diff(y)) ))
完整代码:
import numpy as np; np.random.seed(5)
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
x = np.arange(10)
y = np.random.choice(10,10)
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
cm = dict(zip(range(-1,2,1),list("rbg")))
colors = list( map( cm.get , np.sign(np.diff(y)) ))
lc = LineCollection(segments, colors=colors, linewidths=2)
fig, ax = plt.subplots()
ax.add_collection(lc)
ax.autoscale()
ax.margins(0.1)
plt.show()