Looks simple but I am not able to draw a X-Y chart with "dots" in pandas DataFrame.
I want to show the subid as "Mark" on X Y Chart with X as age and Y as fdg .
Code so far
mydata = [{'subid': 'B14-111', 'age': 75, 'fdg': 3}, {'subid': 'B14-112', 'age': 22, 'fdg': 2}, {'subid': 'B14-112', 'age': 40, 'fdg': 5}]
df = pandas.DataFrame(mydata)
DataFrame.plot(df,x="age",y="fdg")
show()
df.plot() will accept matplotlib kwargs. See the docs
mydata = [{'subid': 'B14-111', 'age': 75, 'fdg': 3}, {'subid': 'B14-112', 'age': 22,
'fdg': 2}, {'subid': 'B14-112', 'age': 40, 'fdg': 5}]
df = pandas.DataFrame(mydata)
df = df.sort(['age']) # dict doesn't preserve order
df.plot(x='age', y='fdg', marker='.')
Reading your question again, I'm thinking you might actually be asking for a scatterplot.
import matplotlib.pyplot as plt
plt.scatter(df['age'], df['fdg'])
Have a look at the matplotlib docs.
Try following for a scatter diagram.
import pandas
from matplotlib import pyplot as plt
mydata = [{'subid': 'B14-111', 'age': 75, 'fdg': 3}, {'subid': 'B14-112', 'age': 22,
'fdg': 2}, {'subid': 'B14-112', 'age': 40, 'fdg': 5}]
df = pandas.DataFrame(mydata)
x,y = [],[]
x.append (df.age)
y.append (df.fdg)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(y,x,'o-')
plt.show()
Related
I have created Highcharts graph by this code:
def chart_data(request):
dataset = DispatchPlan.objects.annotate(month=TruncMonth('scheduled_date')).values('month').annotate(
c=Sum('weight')).values('month', 'c')
chart = {
'chart': {'type': 'column'},
'title': {'text': 'Weight Dispatched by Months'},
'series': [{
'name': 'Months',
'data': [{'name': row['month'], 'y': row["c"]} for row in dataset]
}]
}
return JsonResponse(chart)
How can I add the X axis labels such that it shows month name instead of 0 and 1 ?
This is the one row of dataset from which the graph is plotted
{'month': datetime.datetime(2019, 6, 1, 0, 0, tzinfo=<DstTzInfo 'Asia/Kolkata' IST+5:30:00 STD>), 'c': 17600}
Try to use strftime (documentation) like that :
{'month': datetime.datetime(2019, 6, 1, 0, 0, tzinfo=<DstTzInfo 'Asia/Kolkata' IST+5:30:00 STD>).strftime("%B"), 'c': 17600}
I have the following code from edited from: How to plot pie charts as subplots with custom size with Plotly in Python
import plotly
import plotly.offline as py
import plotly.graph_objs as go
py.init_notebook_mode(connected=True)
labels = ['Oxygen','Hydrogen','Carbon_Dioxide','Nitrogen']
values = [4500,2500,1053,500]
domains = [
{'x': [0.0, 0.33], 'y': [0.0, 0.50]},
{'x': [0.33, 0.66], 'y': [0.0, 0.50]},
{'x': [0.66, 1], 'y': [0.0, 0.50]},
{'x': [0.0, 0.33], 'y': [0.50, 1]},
{'x': [0.33, 0.66], 'y': [0.50, 1]},
{'x': [0.66, 1], 'y': [0.50, 1]},
]
traces = []
valueslist = []
for domain in domains:
trace = go.Pie(labels = labels,
values = values,
domain = domain)
traces.append(trace)
layout = go.Layout(height = 600,
width = 600,
autosize = False,
title = 'Main title')
fig = go.Figure(data = traces, layout = layout)
py.iplot(fig, show_link = False, image='png')
I am trying to plot 6 pie charts at one time with different values and different titles for each chart. How should I add these extra lists? Assume, I have the following lists to add:
values1 = [5, 6, 1, 2]
values2 = [1, 4, 5, 6]
values3 = [2, 6, 2, 4]
values4 = [1, 5, 3, 7]
values5 = [25, 51, 33, 47]
#with following titles:
title = 'title0'
title1 = 'title1'
title2 = 'title2'
title3 = 'title3'
title4 = 'title4'
title5 = 'title5'
Example creation of Dictionary: Dictionary processes Elements in arbitrary fashion. Hence I get the output in mixed order which doesnt correlate with my list x.
x = [100,2,300,4,75]
dct = {}
for i in x:
dct['lst_%s' % i] = []
for z in range(0,5):
dct['lst_%s' % i].extend((x[z],x[z-1]))
print(dct)
{'lst_300': [100, 75, 2, 100, 300, 2, 4, 300, 75, 4], 'lst_75': [100, 75, 2, 100, 300, 2, 4, 300, 75, 4], 'lst_100': [100, 75, 2, 100, 300, 2, 4, 300, 75, 4], 'lst_2': [100, 75, 2, 100, 300, 2, 4, 300, 75, 4], 'lst_4': [100, 75, 2, 100, 300, 2, 4, 300, 75, 4]}
Using sorted key I do get dictionary headers in order corresponding to my list x but how can I retrieve the elements for the same ?
x = [100,2,300,4,75]
dct = {}
for i in x:
dct['lst_%s' % i] = []
for z in range(0,5):
dct['lst_%s' % i].extend((x[z],x[z-1]))
print(sorted(dct))
['lst_100', 'lst_2', 'lst_300', 'lst_4', 'lst_75']
dict is unordered by definition. If you really want an ordered map, use collections.OrderedDict
names=['Peter', 'John']
size = ['X', 'M', 'L']
list_price = [1, 2, 3, 4, 5, 6] # There are 2 people will buy 3 size of shirt
I want to create my data structure into:
[
{'name': u'Peter', 'size_price': defaultdict(<type 'int'>, { 'X': 1, 'M':2, 'L': 3})},
{'name': 'John', 'size_price': defaultdict(<type 'int'>, {'X':4, 'M':5, 'L':6})}
]
I prefer to do defaultdict()
You can turn list_price into an iterator and then use next to get one value after the other:
>>> iterator = iter(list_price)
>>> [{"name": n, "size_price": {s: next(iterator) for s in size}} for n in names]
[{'size_price': {'X': 1, 'M': 2, 'L': 3}, 'name': 'Peter'},
{'size_price': {'X': 4, 'M': 5, 'L': 6}, 'name': 'John'}]
Of course you do not have to use a list comprehension but can do the same thing with nested loops as well.
My View.py:
from django.db.models import Count
def test1(request):
states = Loksabha.objects.values('state').distinct('state')
terms = Loksabha.objects.values('term').distinct('term')
dataset = Loksabha.objects.all()
state_filter=Loksabha.objects.filter(state='Maharashtra',term='Fourteenth Lok Sabha(2004- 09)').annotate(num=Count('party',distinct=True))
age_filter=state_filter.values('party').annotate(Count('party'))
xdata=[]
ydata=[]
for b in state_filter:
xdata.append(b.party)
ydata.append(b.num)
chartdata = {'x': xdata, 'y': ydata}
charttype = "pieChart"
chartcontainer = 'piechart_container'
i have used django-nvd3 to display the graph my state_filter query answer is coreect but i cant understand the pass the value of ValueQueryset to xdata[] and ydata[]. my state_filter queryset value pass to the age_filter
age_filter value is:
[{'party': 'Shiv Sena', 'party__count': 14},
{'party': 'Indian Nationlist Congress', 'party__count': 15},
{'party': 'Nationlist Congress Party', 'party__count': 9},
{'party': 'Republican Party of India(A)', 'party__count': 1},
{'party': 'Bharatiya Janata Party', 'party__count': 14},
{'party': 'Independent', 'party__count': 1}]
ValueQuerySet yields dictionaries. Get items by indexing, instead of accessing attributes.
Replace following lines:
for b in state_filter:
xdata.append(b.party)
ydata.append(b.num)
with:
for d in age_filter:
xdata.append(b['party'])
ydata.append(b['party_count'])