英文:
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()
答案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 :
-
use your dictionnary and follow https://stackoverflow.com/questions/21822592/plot-a-scatter-plot-in-python-with-matplotlib-with-dictionary (use of
matplotlib.pyplot.scatter
) -
convert your dictionnary to dataframe with
pd.DataFrame.from_dict(data)
and then usepandas.DataFrame.plot.scatter(x=x, y=y)
答案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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论