Добавить текст в горизонтальные полосы pandas [duplicate]

Используйте функцию callback() внутри успеха foo(). Попробуйте таким образом. Это просто и легко понять. & nbsp;

var lat = "";
var lon = "";
function callback(data) {
    lat = data.lat;
    lon = data.lon;
}
function getLoc() {
    var url = "http://ip-api.com/json"
    $.getJSON(url, function(data) {
        callback(data);
    });
}

getLoc();
34
задан Franck Dernoncourt 14 May 2015 в 01:55
поделиться

3 ответа

Добавить:

for i, v in enumerate(y):
    ax.text(v + 3, i + .25, str(v), color='blue', fontweight='bold')

результат:

enter image description here [/g0]

Значения y v являются как x- местоположение и строковые значения для ax.text, и, как правило, штрих-код имеет метрику по 1 для каждого бара, поэтому перечисление i является y-местом.

62
ответ дан cphlewis 27 August 2018 в 11:03
поделиться

Я заметил, что код примера api содержит пример barchart со значением строки, отображаемой на каждом баре:

"""
========
Barchart
========

A bar plot with errorbars and height labels on individual bars
"""
import numpy as np
import matplotlib.pyplot as plt

N = 5
men_means = (20, 35, 30, 35, 27)
men_std = (2, 3, 4, 1, 2)

ind = np.arange(N)  # the x locations for the groups
width = 0.35       # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(ind, men_means, width, color='r', yerr=men_std)

women_means = (25, 32, 34, 20, 25)
women_std = (3, 5, 2, 3, 3)
rects2 = ax.bar(ind + width, women_means, width, color='y', yerr=women_std)

# add some text for labels, title and axes ticks
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind + width / 2)
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))

ax.legend((rects1[0], rects2[0]), ('Men', 'Women'))


def autolabel(rects):
    """
    Attach a text label above each bar displaying its height
    """
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
                '%d' % int(height),
                ha='center', va='bottom')

autolabel(rects1)
autolabel(rects2)

plt.show()

output:

FYI Что такое единица переменной высоты в «barh» matplotlib? (на данный момент нет простого способа установить фиксированная высота для каждого бара)

9
ответ дан Community 27 August 2018 в 11:03
поделиться

Я знаю, что это старая нить, но я приземлился здесь несколько раз через Google и думаю, что никакой ответ пока не удовлетворен. Попробуйте использовать одну из следующих функций:

def label_bar(ax, bars, text_format, is_inside=True, **kwargs):
    """
    Attach a text label to each bar displaying its y value
    """
    max_y_value = max(bar.get_height() for bar in bars)
    if is_inside:
        distance = max_y_value * 0.05
    else:
        distance = max_y_value * 0.01

    for bar in bars:
        text = text_format.format(bar.get_height())
        text_x = bar.get_x() + bar.get_width() / 2
        if is_inside:
            text_y = bar.get_height() - distance
        else:
            text_y = bar.get_height() + distance

        ax.text(text_x, text_y, text, ha='center', va='bottom', **kwargs)


def label_barh(ax, bars, text_format, is_inside=True, **kwargs):
    """
    Attach a text label to each horizontal bar displaying its y value
    """
    max_y_value = max(bar.get_height() for bar in bars)
    if is_inside:
        distance = max_y_value * 0.05
    else:
        distance = max_y_value * 0.01


    for bar in bars:
        text = text_format.format(bar.get_width())
        if is_inside:
            text_x = bar.get_width() - distance
        else:
            text_x = bar.get_width() + distance
        text_y = bar.get_y() + bar.get_height() / 2

        ax.text(text_x, text_y, text, va='center', **kwargs)

Теперь вы можете использовать их для обычных графиков:

bars = ax.bar(x_pos, values, width=0.5, align="center")
value_format = "{:.1%}"  # displaying values as percentage with one fractional digit
label_bar(ax, bars, value_format, is_inside=True, color="white")

или для графиков на горизонтальной панели:

horizontal_bars = ax.barh(y_pos, values, width=0.5, align="center")
value_format = "{:.1%}"  # displaying values as percentage with one fractional digit
label_barh(ax, horizontal_bars, value_format, is_inside=False, fontweight="bold")
2
ответ дан SaturnFromTitan 27 August 2018 в 11:03
поделиться
Другие вопросы по тегам:

Похожие вопросы: