玩具问题:
import matplotlib.pyplot as plt
x = [10, 11, 12, 15]
y = [5, 7, 4, 3]
z = ["a", "b", "c", "d"]
fig, ax = plt.subplots(figsize = (6, 6))
ax.bar(x, y)
for i, j in enumerate(zip(y, z)):
plt.text(i + 10, j[0] - 0.3, s = str(j[0]), color = 'white')
plt.text(i + 10, j[0] + 0.1, s = str(j[1]), color = 'black')
plt.show()
这会创建一个绘图,其实际值作为文本标签,很不错。文本标签未在每个小节上方对齐,因为x值之间存在间隙。
不用担心,可以插入一些数据:
import matplotlib.pyplot as plt
x = [10, 11, 12, 15]
y = [5, 7, 4, 3]
z = ["a", "b", "c", "d"]
x.insert(3, 13)
x.insert(4, 14)
y.insert(3, 0)
y.insert(4, 0)
z.insert(3, ' ')
z.insert(4, ' ')
fig, ax = plt.subplots(figsize = (6, 6))
ax.bar(x, y)
# ax.set_yscale('log')
for i, j in enumerate(zip(y, z)):
plt.text(i + 10, j[0] - 0.3, s = str(j[0]), color = 'white')
plt.text(i + 10, j[0] + 0.1, s = str(j[1]), color = 'black')
plt.show()
甜,正是我们想要的,美丽的情节。
但是...
# ax.set_yscale('log')
如果未注释set_yscale('log'):
ValueError: Image size of 384x806494 pixels is too large. It must be less than 2^16 in each direction.
因此您在y值中不能有0,因为未定义log 0。很有道理。
除了现在,我无法解决原始问题,因为0不能用来表示一个空的条。
log 1 = 0,但是如果您插入1,则仍然显示条形,因为我想是原因?
对于matplotlib版本'2.2.3',是否有任何解决方法?如果不能使用0,怎么办?
谢谢
一种解决方法是在绘制并以线性比例绘制之前记录您的y值:
import matplotlib.pyplot as plt
import numpy as np
x = [10, 11, 12, 15]
y = [5, 7, 4, 3]
z = ["a", "b", "c", "d"]
x.insert(3, 13)
x.insert(4, 14)
y.insert(3, 0)
y.insert(4, 0)
z.insert(3, ' ')
z.insert(4, ' ')
fig, ax = plt.subplots(figsize = (6, 6))
mask = ~np.isinf(np.log(y)) # get mask of non-inf values
ax.bar(np.array(x)[mask], np.log(y)[mask]) # plot only non-inf values
for i, j in enumerate(zip(y, z)):
if not j[0]:
continue
plt.text(i + 10, np.log(j[0]) - 0.08, s = str(j[0]), color = 'white')
plt.text(i + 10, np.log(j[0]) + 0.02, s = str(j[1]), color = 'black')
plt.show()
我必须更改文本的y值以使其看起来不错。看一下下面的结果: