简体   繁体   English

Python matplotlib 多条

[英]Python matplotlib multiple bars

How to plot multiple bars in matplotlib, when I tried to call the bar function multiple times, they overlap and as seen the below figure the highest value red can be seen only.如何在 matplotlib 中绘制多个条形图,当我尝试多次调用 bar 函数时,它们重叠,如下图所示,只能看到最高值红色。 How can I plot the multiple bars with dates on the x-axes?如何在 x 轴上绘制带有日期的多个条形图?

So far, I tried this:到目前为止,我试过这个:

import matplotlib.pyplot as plt
import datetime

x = [
    datetime.datetime(2011, 1, 4, 0, 0),
    datetime.datetime(2011, 1, 5, 0, 0),
    datetime.datetime(2011, 1, 6, 0, 0)
]
y = [4, 9, 2]
z = [1, 2, 3]
k = [11, 12, 13]

ax = plt.subplot(111)
ax.bar(x, y, width=0.5, color='b', align='center')
ax.bar(x, z, width=0.5, color='g', align='center')
ax.bar(x, k, width=0.5, color='r', align='center')
ax.xaxis_date()

plt.show()

I got this:我懂了:

在此处输入图像描述

The results should be something like, but with the dates are on the x-axes and bars are next to each other:结果应该是这样的,但是日期在 x 轴上,条形彼此相邻:

在此处输入图像描述

import matplotlib.pyplot as plt
from matplotlib.dates import date2num
import datetime

x = [
    datetime.datetime(2011, 1, 4, 0, 0),
    datetime.datetime(2011, 1, 5, 0, 0),
    datetime.datetime(2011, 1, 6, 0, 0)
]
x = date2num(x)

y = [4, 9, 2]
z = [1, 2, 3]
k = [11, 12, 13]

ax = plt.subplot(111)
ax.bar(x-0.2, y, width=0.2, color='b', align='center')
ax.bar(x, z, width=0.2, color='g', align='center')
ax.bar(x+0.2, k, width=0.2, color='r', align='center')
ax.xaxis_date()

plt.show()

在此处输入图像描述

I don't know what's the "y values are also overlapping" means, does the following code solve your problem?我不知道“y 值也重叠”是什么意思,下面的代码能解决你的问题吗?

ax = plt.subplot(111)
w = 0.3
ax.bar(x-w, y, width=w, color='b', align='center')
ax.bar(x, z, width=w, color='g', align='center')
ax.bar(x+w, k, width=w, color='r', align='center')
ax.xaxis_date()
ax.autoscale(tight=True)

plt.show()

在此处输入图像描述

The trouble with using dates as x-values, is that if you want a bar chart like in your second picture, they are going to be wrong.使用日期作为 x 值的问题在于,如果您想要第二张图片中的条形图,那么它们将是错误的。 You should either use a stacked bar chart (colours on top of each other) or group by date (a "fake" date on the x-axis, basically just grouping the data points).您应该使用堆叠条形图(颜色相互叠加)或按日期分组(x 轴上的“假”日期,基本上只是对数据点进行分组)。

import numpy as np
import matplotlib.pyplot as plt

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

fig = plt.figure()
ax = fig.add_subplot(111)

yvals = [4, 9, 2]
rects1 = ax.bar(ind, yvals, width, color='r')
zvals = [1,2,3]
rects2 = ax.bar(ind+width, zvals, width, color='g')
kvals = [11,12,13]
rects3 = ax.bar(ind+width*2, kvals, width, color='b')

ax.set_ylabel('Scores')
ax.set_xticks(ind+width)
ax.set_xticklabels( ('2011-Jan-4', '2011-Jan-5', '2011-Jan-6') )
ax.legend( (rects1[0], rects2[0], rects3[0]), ('y', 'z', 'k') )

def autolabel(rects):
    for rect in rects:
        h = rect.get_height()
        ax.text(rect.get_x()+rect.get_width()/2., 1.05*h, '%d'%int(h),
                ha='center', va='bottom')

autolabel(rects1)
autolabel(rects2)
autolabel(rects3)

plt.show()

在此处输入图像描述

after looking for a similar solution and not finding anything flexible enough, I decided to write my own function for it.在寻找类似的解决方案但没有找到足够灵活的东西后,我决定为它编写自己的函数。 It allows you to have as many bars per group as you wish and specify both the width of a group as well as the individual widths of the bars within the groups.它允许您在每组中拥有任意数量的条,并指定组的宽度以及组内条的各个宽度。

Enjoy:享受:

from matplotlib import pyplot as plt


def bar_plot(ax, data, colors=None, total_width=0.8, single_width=1, legend=True):
    """Draws a bar plot with multiple bars per data point.

    Parameters
    ----------
    ax : matplotlib.pyplot.axis
        The axis we want to draw our plot on.

    data: dictionary
        A dictionary containing the data we want to plot. Keys are the names of the
        data, the items is a list of the values.

        Example:
        data = {
            "x":[1,2,3],
            "y":[1,2,3],
            "z":[1,2,3],
        }

    colors : array-like, optional
        A list of colors which are used for the bars. If None, the colors
        will be the standard matplotlib color cyle. (default: None)

    total_width : float, optional, default: 0.8
        The width of a bar group. 0.8 means that 80% of the x-axis is covered
        by bars and 20% will be spaces between the bars.

    single_width: float, optional, default: 1
        The relative width of a single bar within a group. 1 means the bars
        will touch eachother within a group, values less than 1 will make
        these bars thinner.

    legend: bool, optional, default: True
        If this is set to true, a legend will be added to the axis.
    """

    # Check if colors where provided, otherwhise use the default color cycle
    if colors is None:
        colors = plt.rcParams['axes.prop_cycle'].by_key()['color']

    # Number of bars per group
    n_bars = len(data)

    # The width of a single bar
    bar_width = total_width / n_bars

    # List containing handles for the drawn bars, used for the legend
    bars = []

    # Iterate over all data
    for i, (name, values) in enumerate(data.items()):
        # The offset in x direction of that bar
        x_offset = (i - n_bars / 2) * bar_width + bar_width / 2

        # Draw a bar for every value of that type
        for x, y in enumerate(values):
            bar = ax.bar(x + x_offset, y, width=bar_width * single_width, color=colors[i % len(colors)])

        # Add a handle to the last drawn bar, which we'll need for the legend
        bars.append(bar[0])

    # Draw legend if we need
    if legend:
        ax.legend(bars, data.keys())


if __name__ == "__main__":
    # Usage example:
    data = {
        "a": [1, 2, 3, 2, 1],
        "b": [2, 3, 4, 3, 1],
        "c": [3, 2, 1, 4, 2],
        "d": [5, 9, 2, 1, 8],
        "e": [1, 3, 2, 2, 3],
        "f": [4, 3, 1, 1, 4],
    }

    fig, ax = plt.subplots()
    bar_plot(ax, data, total_width=.8, single_width=.9)
    plt.show()

Output:输出:

在此处输入图像描述

I know that this is about matplotlib , but using pandas and seaborn can save you a lot of time:我知道这是关于matplotlib的,但是使用pandasseaborn可以为您节省很多时间:

df = pd.DataFrame(zip(x*3, ["y"]*3+["z"]*3+["k"]*3, y+z+k), columns=["time", "kind", "data"])
plt.figure(figsize=(10, 6))
sns.barplot(x="time", hue="kind", y="data", data=df)
plt.show()

在此处输入图像描述

  • Given the existing answers, the easiest solution, given the data in the OP, is load the data into a dataframe and plot with pandas.DataFrame.plot .给定现有答案,给定 OP 中的数据,最简单的解决方案是将数据加载到数据框中并使用pandas.DataFrame.plot进行绘图。
    • Load the value lists into pandas with a dict , and specify x as the index.使用dict将值列表加载到 pandas 中,并指定x作为索引。 The index will automatically be set as the x-axis, and the columns will be plotted as the bars.索引将自动设置为 x 轴,列将绘制为条形图。
    • pandas.DataFrame.plot uses matplotlib as the default backend. pandas.DataFrame.plot使用matplotlib作为默认后端。
  • See How to add value labels on a bar chart for thorough details about using .bar_label .有关使用.bar_label的详细信息,请参阅如何在条形图上添加值标签
  • Tested in python 3.8.11 , pandas 1.3.2 , matplotlib 3.4.3python 3.8.11pandas 1.3.2matplotlib 3.4.3中测试
import pandas as pd

# using the existing lists from the OP, create the dataframe
df = pd.DataFrame(data={'y': y, 'z': z, 'k': k}, index=x)

# since there's no time component and x was a datetime dtype, set the index to be just the date
df.index = df.index.date

# display(df)
            y  z   k
2011-01-04  4  1  11
2011-01-05  9  2  12
2011-01-06  2  3  13

# plot bars or kind='barh' for horizontal bars; adjust figsize accordingly
ax = df.plot(kind='bar', rot=0, xlabel='Date', ylabel='Value', title='My Plot', figsize=(6, 4))

# add some labels
for c in ax.containers:
    # set the bar label
    ax.bar_label(c, fmt='%.0f', label_type='edge')
    
# add a little space at the top of the plot for the annotation
ax.margins(y=0.1)

# move the legend out of the plot
ax.legend(title='Columns', bbox_to_anchor=(1, 1.02), loc='upper left')

在此处输入图像描述

  • Horizontal bars for when there are more columns有更多列时的水平条
ax = df.plot(kind='barh', ylabel='Date', title='My Plot', figsize=(5, 4))
ax.set(xlabel='Value')
for c in ax.containers:
    # set the bar label
    ax.bar_label(c, fmt='%.0f', label_type='edge')
    
ax.margins(x=0.1)

# move the legend out of the plot
ax.legend(title='Columns', bbox_to_anchor=(1, 1.02), loc='upper left')

在此处输入图像描述

I modified pascscha's solution extending the interface, hopefully this helps someone else!我修改了 pascscha 扩展界面的解决方案,希望这对其他人有帮助! Key features:主要特征:

  • Variable number of entries per bar group每个栏组的可变条目数
  • Customizable colors可定制的颜色
  • Handling of x ticks处理 x 刻度
  • Fully customizable bar labels on top of bars条形顶部完全可定制的条形标签
def bar_plot(ax, data, group_stretch=0.8, bar_stretch=0.95,
             legend=True, x_labels=True, label_fontsize=8,
             colors=None, barlabel_offset=1,
             bar_labeler=lambda k, i, s: str(round(s, 3))):
    """
    Draws a bar plot with multiple bars per data point.
    :param dict data: The data we want to plot, wher keys are the names of each
      bar group, and items is a list of bar values for the corresponding group.
    :param float group_stretch: 1 means groups occupy the most (largest groups
      touch side to side if they have equal number of bars).
    :param float bar_stretch: If 1, bars within a group will touch side to side.
    :param bool x_labels: If true, x-axis will contain labels with the group
      names given at data, centered at the bar group.
    :param int label_fontsize: Font size for the label on top of each bar.
    :param float barlabel_offset: Distance, in y-values, between the top of the
      bar and its label.
    :param function bar_labeler: If not None, must be a functor with signature
      ``f(group_name, i, scalar)->str``, where each scalar is the entry found at
      data[group_name][i]. When given, returns a label to put on the top of each
      bar. Otherwise no labels on top of bars.
    """
    sorted_data = list(sorted(data.items(), key=lambda elt: elt[0]))
    sorted_k, sorted_v  = zip(*sorted_data)
    max_n_bars = max(len(v) for v in data.values())
    group_centers = np.cumsum([max_n_bars
                               for _ in sorted_data]) - (max_n_bars / 2)
    bar_offset = (1 - bar_stretch) / 2
    bars = defaultdict(list)
    #
    if colors is None:
        colors = {g_name: [f"C{i}" for _ in values]
                  for i, (g_name, values) in enumerate(data.items())}
    #
    for g_i, ((g_name, vals), g_center) in enumerate(zip(sorted_data,
                                                         group_centers)):
        n_bars = len(vals)
        group_beg = g_center - (n_bars / 2) + (bar_stretch / 2)
        for val_i, val in enumerate(vals):
            bar = ax.bar(group_beg + val_i + bar_offset,
                         height=val, width=bar_stretch,
                         color=colors[g_name][val_i])[0]
            bars[g_name].append(bar)
            if  bar_labeler is not None:
                x_pos = bar.get_x() + (bar.get_width() / 2.0)
                y_pos = val + barlabel_offset
                barlbl = bar_labeler(g_name, val_i, val)
                ax.text(x_pos, y_pos, barlbl, ha="center", va="bottom",
                        fontsize=label_fontsize)
    if legend:
        ax.legend([bars[k][0] for k in sorted_k], sorted_k)
    #
    ax.set_xticks(group_centers)
    if x_labels:
        ax.set_xticklabels(sorted_k)
    else:
        ax.set_xticklabels()
    return bars, group_centers

Sample run:样品运行:

fig, ax = plt.subplots()
data = {"Foo": [1, 2, 3, 4], "Zap": [0.1, 0.2], "Quack": [6], "Bar": [1.1, 2.2, 3.3, 4.4, 5.5]}
bar_plot(ax, data, group_stretch=0.8, bar_stretch=0.95, legend=True,
         labels=True, label_fontsize=8, barlabel_offset=0.05,
         bar_labeler=lambda k, i, s: str(round(s, 3)))
fig.show()

在此处输入图像描述

I did this solution: if you want plot more than one plot in one figure, make sure before plotting next plots you have set right matplotlib.pyplot.hold(True) to able adding another plots.我做了这个解决方案:如果您想在一个图中绘制多个图,请确保在绘制下一个图之前您已设置正确的matplotlib.pyplot.hold(True)以添加另一个图。

Concerning the datetime values on the X axis, a solution using the alignment of bars works for me.关于 X 轴上的日期时间值,使用条形对齐的解决方案对我有用。 When you create another bar plot with matplotlib.pyplot.bar() , just use align='edge|center' and set width='+|-distance' .当您使用matplotlib.pyplot.bar()创建另一个条形图时,只需使用align='edge|center'并设置width='+|-distance'

When you set all bars (plots) right, you will see the bars fine.当您正确设置所有条形图(图)时,您会看到条形图正常。

Dont do this with matplotlib is way more complicated.不要用 matplotlib 这样做会更复杂。 The best is to use seaborn:最好是使用seaborn:

here: https://seaborn.pydata.org/generated/seaborn.barplot.html在这里: https : //seaborn.pydata.org/generated/seaborn.barplot.html

$ pip install matplotlib==3.5.0 Install this library as most notebooks support older versions (older than 3.3) $ pip install matplotlib==3.5.0 安装这个库,因为大多数笔记本都支持旧版本(早于 3.3)

import matplotlib.pyplot as plt
import numpy as np


labels = ['I1', 'I2', 'I3', 'I4', 'I5', 'I6', 'I7', 'I8', 'I9', 'I10']
sample1 = [0.2, 0.34, 0.30, 0.35, 0.27, 0.25, 0.32, 0.34, 0.20, 0.25]
sample2 = [0.25, 0.32, 0.34, 0.20, 0.25, 0.2, 0.34, 0.30, 0.35, 0.27]

x = np.arange(len(labels))  # the label locations
width = 0.35  # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(x - width/2, sample1, width, label='Error 1')
rects2 = ax.bar(x + width/2, sample2, width, label='Error 2')

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('Error', fontweight='bold', fontsize=16)
ax.set_xlabel('Images', fontweight='bold', fontsize=16)
ax.set_title("Error Mapping", fontweight='bold', fontsize=20)
ax.set_xticks(x, labels)
ax.legend()

ax.bar_label(rects1, padding=3)
ax.bar_label(rects2, padding=3)

fig.tight_layout()

plt.show()

Optput:选择: 输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM