当前位置: 首页 > 知识库问答 >
问题:

如何绘制字典

鲍钊
2023-03-14

我在绘制以下值时遇到一些问题:

my_dict={'word1': ['31', '131', '2'], 'word2': ['42', '33', '154', '21']}

我所做的是

plt.bar(my_dict.keys(), my_dict.values(), color='g')

但我有一个错误:

TypeError:ufunc“add”不包含签名类型与dtype匹配的循环('

那么我已经试过了

plt.plot(*zip(*sorted(my_dict.items())))
plt.show()

但我还有另外一个错误:

TypeError:不可损坏的类型:“列表”

我对频率感兴趣。

我该怎么做才能修好它?

从原始数据集(因为我在复制代码时遇到了一些错误):

my_dict = defaultdict(list)

print({ k : v for k, v in my_dict.items() })

输出:

{'word1': ['122', '121.2', '132', '132', '144', '144.5', '144', '150', '150,5', '150,5', '150,5'], 'word2': ['230', '230', '230', '230'], 'word3': ['542', '542', '540'], 'word4': ['134', '134']}

我需要绘制每个单词中值的频率(例如,对于单词1,132和144的频率应为2,然后150.5的频率应为3,所有其他值的频率应为1)。

共有2个答案

和和煦
2023-03-14
  • Pandas要求列的长度相同,因此zip\u longest将用None填充空格
  • 根据您希望打印数据的方式,有许多选项可以塑造数据的形状
import pandas as pd
from itertools import zip_longest
import matplotlib.pyplot as plt

# data
d = {'word1': ['122', '121.2', '132', '132', '144', '144.5', '144', '150', '150.5', '150.5', '150.5'], 'word2': ['230', '230', '230', '230'], 'word3': ['542', '542', '540'], 'word4': ['134', '134']}

# since the values lists are uneven
cols = d.keys()
val = list(zip_longest(*d.values()))

# dataframe
df = pd.DataFrame(val, columns=cols, dtype=float)

    word1  word2  word3  word4
0   122.0  230.0  542.0  134.0
1   121.2  230.0  542.0  134.0
2   132.0  230.0  540.0    NaN
3   132.0  230.0    NaN    NaN
4   144.0    NaN    NaN    NaN
5   144.5    NaN    NaN    NaN
6   144.0    NaN    NaN    NaN
7   150.0    NaN    NaN    NaN
8   150.5    NaN    NaN    NaN
9   150.5    NaN    NaN    NaN
10  150.5    NaN    NaN    NaN
ax = df.plot.bar()

f = [df[c].value_counts().to_dict() for c in df.columns]  # list of list of value counts
f = dict(kv for d in f for kv in d.items())  # this will break if the values for each word aren't unique

for p in ax.patches:

    if p.get_height() > 0:

        # add value at top of bar
        ax.annotate(format(p.get_height(), '.1f'),
                    (p.get_x() + p.get_width() / 2., p.get_height() + 10),
                    ha = 'center', va = 'center', fontsize=9, rotation=90,
                    xytext = (0, 10), textcoords = 'offset points')

        # add frequency of value at center of bar
        ax.annotate(format(f[p.get_height()], '.0f'),
            (p.get_x() + p.get_width() / 2., p.get_height() / 2),
            ha = 'center', va = 'center', fontsize=9, rotation=0,
            xytext = (0, 10), textcoords = 'offset points')
tdf = df.T  # transpose dataframe df

ax = tdf.plot.bar()

f = [df[c].value_counts().to_dict() for c in df.columns]  # list of list of value counts
f = dict(kv for d in f for kv in d.items())  # this will break if the values for each word aren't unique

for p in ax.patches:

    if p.get_height() > 0:

        # add value at top of bar
        ax.annotate(format(p.get_height(), '.1f'),
                    (p.get_x() + p.get_width() / 2., p.get_height() + 10),
                    ha = 'center', va = 'center', fontsize=9, rotation=90,
                    xytext = (0, 10), textcoords = 'offset points')

        # add frequency of value at center of bar
        ax.annotate(format(f[p.get_height()], '.0f'),
            (p.get_x() + p.get_width() / 2., p.get_height() / 2),
            ha = 'center', va = 'center', fontsize=9, rotation=0,
            xytext = (0, 10), textcoords = 'offset points')
  • hue着色会根据列中由hueword使用的唯一值的数量将条形图偏离中心。
    • 在下面的示例中,所有四个单词都包含值150.5,因此您可以在图中看到它们分组。
    • 只需增加figsize高度即可
    import seaborn as sns
    
    d = {'word1': ['122', '121.2', '132', '132', '144', '144.5', '144', '150', '150.5', '150.5', '150.5'], 'word2': ['230', '230', '230', '230', '150.5'], 'word3': ['542', '542', '540', '150.5'], 'word4': ['134', '134', '150.5']}
    
    cols = d.keys()
    val = list(zip_longest(*d.values()))
    
    # dataframe
    df = pd.DataFrame(val, columns=cols, dtype=float)
    
    # convert from wide to long
    df['id'] = df.index
    dfl = pd.wide_to_long(df, stubnames='word', j='x', i='id').reset_index().rename(columns={'word': 'v', 'x': 'word'}).dropna()
    
    # groupby for frequency counts
    dflg = dfl.groupby('word').agg({'v': 'value_counts'}).rename(columns={'v': 'freq_count'}).reset_index().sort_values('v')
    
    # plot
    plt.figure(figsize=(6, 10))
    p = sns.barplot(y='v', x='freq_count', data=dflg, hue='word', orient='h')
    

    https://imgs.xnip.cn/cj/n/86/d25b3012-c5cd-4005-a6b8-7ace79cbea9b.png" width="100%" height="100%" />

龚玄天
2023-03-14
import matplotlib.pyplot as plt
from numpy import random

mydict={'word1': ['122', '121.2', '132', '132', '144', '144.5', '144', '150', '150,5', '150,5', '150,5'], 'word2': ['230', '230', '230', '230'], 'word3': ['542', '542', '540'], 'word4': ['134', '134']}


for k,l in mydict.items():
    labeled = False
    c=random.rand(3,)
    for v in l:
        if labeled:
            plt.bar(v,len([d for d in l if d==v]),color=c)
        else:
            plt.bar(v,len([d for d in l if d==v]),label=k,color=c)
            labeled = True

plt.legend()
plt.show()
 类似资料:
  • 问题内容: 我试过了 但它产生错误: 任何的想法? 问题答案: 好吧,错误消息很清楚:不是实体。如果要映射基本元素的集合,请使用批注(来自Hibernate)或批注(来自JPA 2.0)。 因此,假设您使用的是Hibernate Annotations 3.4,请尝试以下操作: 或者,使用泛型时: 如果您使用的是Hibernate Annotations 3.5+,则更喜欢JPA 2.0注释: 或

  • 问题内容: 在swing应用程序中,我使用来自定义文本。这是一个示例: 在同一应用中,一个 文本http://img525.imageshack.us/img525/4928/drawstringsample.jpg ,我正在使用渲染文本。这是一个示例: 替代文本http://img28.imageshack.us/img28/1134/jtextpanesample.jpg 您能注意到较低的样本

  • 问题内容: 在问这个之前,我在网上做了很多搜索。我就是做不到。我有点难以理解。那么,如何在与处于世界位置的物体相对应的正确屏幕位置绘制图像?谢谢 如果其他人在同一障碍物前面找到了他,我会发布一个HOW TO,对正常性的很好解释。您可以在这里找到它:http : //romeo.akademx.ro/2012/04/06/slick-and- box2d/ 这是渲染功能: 这些是我用来转换世界屏幕协

  • parameter.size=30; parameter.characters=“abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789.'()>?:”; font=generator.generateFont(参数); gdx.gl20.glclear(GL20.gl_color_buffer_bit); Begin(); f

  • 我编写了这段代码,可以在JavaFX画布上绘制。它可以很好地工作,但我不知道如何重新绘制画布(比如在Swing中),以便在新画布上重新开始绘制。这是我的代码,非常感谢你的帮助!马里奥

  • 问题内容: 我正在尝试制作绘画程序的项目中。到目前为止,我已经使用Netbeans来创建GUI并设置程序。 到目前为止,我已经能够调用在其中绘制所需的所有坐标,但是我对如何在其中实际绘制感到非常困惑。 在我的代码接近尾声时,我在面板内部进行绘制的尝试失败。 谁能在这样的示例中解释/显示如何使用图形? 我发现的所有示例都创建了一个类并对其进行扩展,JPanel但是我不知道是否可以这样做,因为它是在n