我正在使用Matplotlib制作堆积的条形图,并希望显示单击数据的标签。
我写了一个代码来显示简单折线图的标签。当我尝试对条形图执行相同操作时,它不起作用。以下是适用于折线图的代码。
# plots port counts per address as a stacked bar graph
fig=plt.figure()
ax=fig.add_subplot(111)
text=ax.text(0,0, '', va='baseline', ha='left')
bottom=np.array([0,0,0])
# plot
x_pos=np.arange(3)
y=np.array([[1,2,3],[1,3,5]])
for i in range(2):
ax.bar(x_pos, y[i, :], align='center', bottom=bottom, alpha=0.5, gid=i)
# update the bar bases for the next iteration
bottom=np.add(bottom,y[i, :] )
def on_click(event):
gid='-'
for curve in ax.get_lines():
gid='TEST'
if curve.contains(event)[0]:
gid=curve.get_gid()
text.set_text('Class %s' % gid)
fig.canvas.mpl_connect('button_press_event', on_click)
下一个代码可用于绘制堆积的条形图,但不会显示标签。尽管未返回任何错误消息,但无法获取和显示标签。
ax.bar
我假设get_lines
不会创建要由for curve in ax.get_lines()
重调的线,因此它会以0次迭代退出const express = require('express');
var app = express();
const mongoose = require('mongoose'),
Admin = mongoose.mongo.Admin;
const port = 3002
mongoose.set('debug', true)
var db = mongoose.createConnection('mongodb://localhost:22222/myapp', {
useNewUrlParser: true }, () => {
console.log('Connection db established')
})
app.use((req, res, next) => {
console.log(req.url + ' ' + new Date());
next();
});
const Cat = mongoose.model('cats', { name: String });
db.on('open', function (err, data) {
new Admin(db.db).command({ currentOp: 1, '$all': true }, (err, r) => {
var connections = []
console.log(err)
console.log(r.inprog.length)
r.inprog.forEach((conn) => {
if (conn.client) {
console.log(conn.client)
connections.push({ thread: conn.threadId, connection: conn.connectionId, op: conn.opid })
}
})
console.log(connections)
})
});
app.listen(port, () => {
console.log('Server started')
})
循环,因为单击图表时如何设置文本如下图所示。
我想知道如何通过单击堆积的条形图来显示标签。
答案 0 :(得分:0)
使用鼠标悬停时,找出包含鼠标事件的艺术家的概念非常有用。 How to annotate the values of X and Y while hovering mouse over the bar graph
相反,在这里您要单击条形图。这是通过“选择器”完成的;实际上,在这种情况下,线条或线条之间没有区别。
因此,以下两种情况均适用。单击第一栏时,显示“班级栏:0”,第一行显示“班级栏:0”。
import numpy as np
import matplotlib.pyplot as plt
# plots port counts per address as a stacked bar graph
fig=plt.figure()
ax=fig.add_subplot(111)
text=ax.text(0,0, '', va='baseline', ha='left')
bottom=np.array([0,0,0])
# plot
x_pos=np.arange(3)
y=np.array([[1,2,3],[1,3,5]])
for i in range(2):
ax.bar(x_pos, y[i, :], align='center', bottom=bottom, alpha=0.5, gid=f"bar: {i}", picker=4)
ax.plot(y[i, :], gid=f"line: {i}", picker=4)
# update the bar bases for the next iteration
bottom=np.add(bottom,y[i, :] )
def on_click(event):
text.set_text(f"Class {event.artist.get_gid()}")
fig.canvas.draw_idle()
fig.canvas.mpl_connect('pick_event', on_click)
plt.show()