绘制一个字典的散点图。

huangapple go评论57阅读模式
英文:

plot a scatter graph for a dictionary

问题

请帮忙,我想使用以下代码绘制一个散点图:

pandas.dataframe.plot(kind='scatter', x=x, y=y)

对于这样的字典类型数据:

{'2022-01-30': 50, '2022-01-31': 152, '2022-02-01': 41}

我想知道如何使用字典,因为我需要一个标题。但是它给我报错x未定义x是键y是值。但在图上,x应该是'Date',y应该是'Quantity'。

英文:

Please I need help I want to plot a graph using

pandas.dataframe.plot(kind='scatter' , x=x , y=y )

for a dictionary type {'2022-01-30': 50, '2022-01-31': 152, '2022-02-01': 41 }

Please how can I use dictionary since i need a title

It is giving me the error x is not defined
x is the key and
y is the value

but on the graph x should be 'Date' and y should be 'Quantity'

答案1

得分: 2

你首先需要创建一个DataFrame:

import pandas as pd
import matplotlib.pyplot as plt

data = {'2022-01-30': 50, '2022-01-31': 152, '2022-02-01': 41}
df = pd.Series(data, name='y').rename_axis('x').reset_index()
df.plot(kind='scatter', x='x', y='y')
plt.show()

输出:
绘制一个字典的散点图。

英文:

You have to create a DataFrame first:

import pandas as pd
import matplotlib.pyplot as plt

data = {'2022-01-30': 50, '2022-01-31': 152, '2022-02-01': 41}
df = pd.Series(data, name='y').rename_axis('x').reset_index()
df.plot(kind='scatter', x='x', y='y')
plt.show()

Output:
绘制一个字典的散点图。

答案2

得分: 0

不可以使用数据框函数绘制字典类型。因此有两种可能性:

  • 使用你的字典并参考https://stackoverflow.com/questions/21822592/plot-a-scatter-plot-in-python-with-matplotlib-with-dictionary(使用 matplotlib.pyplot.scatter 函数)

  • 将你的字典转换为数据框,使用 pd.DataFrame.from_dict(data),然后使用 pandas.DataFrame.plot.scatter(x=x, y=y) 函数。

英文:

You can't plot a dict type with a dataframe function. Thus two possibilities :

答案3

得分: 0

只提取键和数值

import matplotlib.pyplot as plt

data = {'2022-01-30': 50, '2022-01-31': 152, '2022-02-01': 41}
x, y = data.keys(), data.values()

plt.scatter(x, y)
英文:

Just take out the keys & values

import matplotlib.pyplot as plt

data = {'2022-01-30': 50, '2022-01-31': 152, '2022-02-01': 41}
x, y = data.keys(), data.values()

plt.scatter(x, y)

huangapple
  • 本文由 发表于 2023年3月8日 16:17:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75670684.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定