【问题标题】:Matplotlib: How make space between 2 string charsMatplotlib:如何在 2 个字符串字符之间留出空间
【发布时间】:2020-05-18 18:35:19
【问题描述】:

我想制作 2 个带空格的图表 如果我写:

x_axis_1 = ['A','B','C']
y_axis_1 = [5,10,15]
y_axis_2 = [7,3,4]
plt.figure(figsize = (15,6))
plt.bar(x_axis_1-0.2, y_axis_1)
plt.bar(x_axis_1+0.2, y_axis_2)
plt.show()

我明白了

TypeError: unsupported operand type(s) for -: 'list' and 'float'

因为x_axis 是字符串

我怎样才能改变这个?

【问题讨论】:

标签: python pandas matplotlib plot charts


【解决方案1】:

你的意思是这样的?

import matplotlib.pyplot as plt

# You can use this to create a figure and axes in one line
# If you want to make 4 plots in a square configuration you'd need
# fig, ((ax1,ax2),(ax3,ax4)) = plt.subplots(nrows=2,ncols=2,figsize=(15,6))
# Google how to do multiplots in matplotlib.
fig, (ax1,ax2) = plt.subplots(nrows=1,ncols=2,figsize=(15,6))

x_axis_1 = ['A','B','C']
y_axis_1 = [5,10,15]
y_axis_2 = [7,3,4]
ax1.bar(x_axis_1, y_axis_1)
ax2.bar(x_axis_1, y_axis_2)
plt.show()

PS:在您的代码中包含 import 语句。不得不自己查看您正在使用的模块,这很烦人。

PSS:在 python 列表上使用减号永远不会起作用,即使它是用数字填充的。如果你想做那种事情,你需要 numpy 数组:

import numpy as np
array = np.array([1,2,3,2,1])
print(array-0.2)

编辑正确的版本:

原来如此:

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(15,6))

# you need to define a bar width for alignment later on
bar_width = 0.35

# Those are just labels, not the positions
x_axis_labels = ['A','B','C']
# Those are just positions, not labels
x_axis_1 = np.arange(len(x_axis_labels))
y_axis_1 = np.array([5,10,15])
y_axis_2 = np.array([7,3,4])

ax.bar(x_axis_1, y_axis_1,bar_width)
ax.bar(x_axis_1+bar_width, y_axis_2,bar_width)

# This sets the number of ticks to the number of labels.
# It also aligns the tick positions with the center of the bars. Notice the + bar_width/2
ax.set_xticks(np.arange(len(x_axis_labels))+bar_width/2)
# This sets the three ticks, which are now at the right positions, to your x_axis_labels
ax.set_xticklabels(x_axis_labels)
plt.show()

PSSS:尝试更准确地表述您的问题。我很难理解你的意思。这个问题也是这个问题的两倍:Python Create Bar Chart Comparing 2 sets of data

PSSSS:业力请。我想达到 420 分。

【讨论】:

  • 我需要在同一图表上的条形旁边创建一个条形。没有两个图表
【解决方案2】:

您的x_axis_1 是一个字符串列表,因此您会收到此错误。您需要传递数值来定位条形。我使用-0.1+0.1 将条形相邻放置。

plt.bar(np.arange(3)-0.1, y_axis_1, width=0.2, align='center')
plt.bar(np.arange(3)+0.1, y_axis_2, width=0.2, align='center')
plt.xticks(range(3), x_axis_1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 2013-12-28
    • 1970-01-01
    • 2015-12-15
    • 2015-02-18
    相关资源
    最近更新 更多