【问题标题】:Python: Connecting list values with array valuesPython:将列表值与数组值连接起来
【发布时间】:2016-10-13 16:59:21
【问题描述】:

我从here 中汲取灵感创建了一个龙卷风情节。它在 y 轴 (a1,b1,c1...) 上标记了输入变量,并在它们旁边绘制了它们各自的相关系数。见下图:

然后,我对相关系数进行排序,首先绘制最高绝对值而不丢失其符号,然后是下一个最高值,依此类推。使用sorted(values,key=abs, reverse=True)。看看下面的结果

如果您注意到,在第二张图片中,即使条形按绝对降序排序,y 轴标签仍然保持不变。

问题:如何使 y 轴标签(变量)连接到相关系数,使其始终与其相关系数相对应。

下面是我的代码:

import numpy as np
from matplotlib import pyplot as plt

#####Importing Data from csv file#####
dataset1 = np.genfromtxt('dataSet1.csv', dtype = float, delimiter = ',', skip_header = 1, names = ['a', 'b', 'c', 'x0'])
dataset2 = np.genfromtxt('dataSet2.csv', dtype = float, delimiter = ',', skip_header = 1, names = ['a', 'b', 'c', 'x0'])
dataset3 = np.genfromtxt('dataSet3.csv', dtype = float, delimiter = ',', skip_header = 1, names = ['a', 'b', 'c', 'x0'])

corr1 = np.corrcoef(dataset1['a'],dataset1['x0'])
corr2 = np.corrcoef(dataset1['b'],dataset1['x0'])
corr3 = np.corrcoef(dataset1['c'],dataset1['x0'])
corr4 = np.corrcoef(dataset2['a'],dataset2['x0'])
corr5 = np.corrcoef(dataset2['b'],dataset2['x0'])
corr6 = np.corrcoef(dataset2['c'],dataset2['x0'])
corr7 = np.corrcoef(dataset3['a'],dataset3['x0'])
corr8 = np.corrcoef(dataset3['b'],dataset3['x0'])
corr9 = np.corrcoef(dataset3['c'],dataset3['x0'])

np.set_printoptions(precision=4)
variables = ['a1','b1','c1','a2','b2','c2','a3','b3','c3']
base = 0  
values = np.array([corr1[0,1],corr2[0,1],corr3[0,1],
                   corr4[0,1],corr5[0,1],corr6[0,1],
                   corr7[0,1],corr8[0,1],corr9[0,1]])
values = sorted(values,key=abs, reverse=True)
# The y position for each variable
ys = range(len(values))[::-1]  # top to bottom   
# Plot the bars, one by one
for y, value in zip(ys, values):
    high_width = base + value
    #print high_width

    # Each bar is a "broken" horizontal bar chart
    plt.broken_barh(
        [(base, high_width)],
        (y - 0.4, 0.8),
        facecolors=['red', 'red'],  # Try different colors if you like
        edgecolors=['black', 'black'],
        linewidth=1)
# Draw a vertical line down the middle
plt.axvline(base, color='black')
# Position the x-axis on the top/bottom, hide all the other spines (=axis lines)
axes = plt.gca()  # (gca = get current axes)
axes.spines['left'].set_visible(False)
axes.spines['right'].set_visible(False)
axes.spines['top'].set_visible(False)
axes.xaxis.set_ticks_position('bottom')
# Make the y-axis display the variables
plt.yticks(ys, variables)

plt.ylim(-2, len(variables))
plt.show()

在此先感谢

【问题讨论】:

  • 类似zip(*sorted(zip(variables, values), key=lambda x: abs(x[1])))[0]
  • @PatrickHaugh:你的建议奏效了。我只需要颠倒顺序即可获得所需的结果。感谢您在这方面的帮助。谢谢!

标签: python python-2.7 matplotlib


【解决方案1】:

使用内置 zip 函数 - 返回一个元组列表,其中第 i 个元组包含来自每个参数序列或可迭代对象的第 i 个元素。但请注意,返回的列表的长度会被截断为最短参数序列的长度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-16
    • 2023-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-19
    相关资源
    最近更新 更多