I have a json file in which I have different data, I need to generate a graph whose legend is "Dates" and whose data is all the viewers of each user. I've been trying to do it all morning, but I have no idea, can someone help me?
{
"Avg": 49,
"Max": 70,
"Dates": ["01/01/2019 01:05", "01/01/2019 01:10", "01/01/2019 01:15", "01/01/2019 01:20", "01/01/2019 01:25", "01/01/2019 01:30", "01/01/2019 01:35"],
"Viewers": [
{
"Name": "User1",
"Viewers": [1,2,3,4,5,6,7]
},
{
"Name": "User2",
"Viewers": [2,3,4,5,6,7,8]
},
{
"Name": "User3",
"Viewers": [3,4,5,6,7,8,9]
},
{
"Name": "User4",
"Viewers": [4,5,6,7,8,9,10]
},
{
"Name": "user5",
"Viewers": [5,6,7,8,9,10,11]
},
{
"Name": "User6",
"Viewers": [6,7,8,9,10,11,12]
},
{
"Name": "User7",
"Viewers": [7,8,9,10,11,12,13]
},
{
"Name": "Total",
"Viewers": [28, 35, 42, 49, 56, 63, 70]
}
]
}
CodePudding user response:
Assume that you have put the json data in a faile named input.json
import json
import matplotlib.pyplot as plt
with open('input.json') as fp:
json_data = json.load(fp)
for v in json_data['Viewers']:
plt.plot(json_data['Dates'], v['Viewers'], label=v['Name'])
plt.legend()
plt.xticks(rotation = 20)
# to save as png, it should be done before plt.show()
plt.savefig('graph.png')
plt.show()
CodePudding user response:
Assuming original question is exact, meaning plot needs to show 'Dates' in Legend, and data should not include Total, only data for each user:
understanding the data:
import pandas as pd import plotly.express as px data = [...] dates = data['Dates'] users = [x['Name'] for x in data['Viewers']] viewers = [x['Viewers'] for x in data['Viewers']][:-1] data_list = [(dates[index], users[index2], y) for index, x in enumerate(viewers) for index2, y in enumerate(x)] df = pd.DataFrame(data_list, columns =['Date', 'User', 'Viewers'])
plotting it:
fig = px.bar(df, y='Viewers', x = 'User', color = 'Date', barmode="group") fig.show()
result: Plot with 'Dates' as legend
That being said, a time series is usually intelligible if timeline is on x axis. However, given the (interview/technical test?) requirements, I believe this is the correct answer.