I'd like to use Python's matplotlib to change the pattern of the horizontal bar graph.
Currently, I can distinguish between red and blue, but I want to be able to distinguish between black and white.
Specifically, I'd like to change it to a dotted line, diagonal line, lattice, polka dot pattern, etc.
Is there any way? I look forward to your kind cooperation.
data.txt
00 0.01619.833
1 0 19.834 52.805
2 0 52.806 84.005
5 0 84.012 107.305
8 0 107.315 128.998
10 0 129.005 138.956
11 0 138.961 145.587
25 1 31.096 56.180
27 1 58.097 64.857
28 1 64.858 66.494
29 1 66.496 89.908
The program is as follows:
#!/usr/bin/env python
# -*-coding:shift_jis-*-
import numpy as np
import matplotlib.pyplot asplt
y,c,x1,x2 = np.loadtxt('data.txt',unpack=True)
color_mapper=np.vectorize(lambdax:{0:'red',1:'blue'}.get(x))
plt.hlines(y, x1, x2, colors=color_mapper(c), lw=10)
plt.margins (0.1)
plt.grid()
plt.show()
With hlines()
(Line2D
object), you can only set
dashed
or dotted
because it is just a line drawing.You will need to draw each rectangle as shown in http://matthiaseisen.com/pp/patterns/p0203/.
#!/usr/bin/env python
import matplotlib.pyplot asplt
import matplotlib.patches as patches
STYLES = [
dict(fill=False, hatch='/', color='red'),
dict(fill=True, hatch='\\', color='blue', alpha=0.5),
]
HEIGHT=1
_,ax=plt.subplots()
with open('data.txt') asf:
for line in f.readlines():
y,c,x1,x2 = line.split()
y=float(y)-HEIGHT/2
x1 = float(x1)
width=float(x2) - x1
c=int(c)
ax.add_patch (patches.Rectangle((x1,y), width, HEIGHT,**(STYLES[c])))
plt.margins (0.1)
plt.grid()
plt.show()
I have never used numpy, so the file loading part is the original Python code.If necessary, reread it as appropriate.
STYLES
summarizes keyword arguments to Rectangle()
.
© 2024 OneMinuteCode. All rights reserved.