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'])
Related
I have some object references of a class like this:
Patient patientOne = Patient('Person A', 'https://images.unsplash.com/photo-1545996124-0501ebae84d0?ixid=MXwxMjA3fDB8MHxzZWFyY2h8OHx8aHVtYW58ZW58MHx8MHw%3D&ixlib=rb-1.2.1&w=1000&q=80',
8, 2, 'Pending', '10-08-2015', true);
Patient patientTwo = Patient('Person B', 'https://images.unsplash.com/photo-1544005313-94ddf0286df2?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTF8fGh1bWFufGVufDB8fDB8&ixlib=rb-1.2.1&w=1000&q=80',
8, 5, 'Cancel', '23-12-2019', false);
Patient patientThree = Patient('Person C', 'https://images.unsplash.com/photo-1554151228-14d9def656e4?ixid=MXwxMjA3fDB8MHxzZWFyY2h8NHx8aHVtYW58ZW58MHx8MHw%3D&ixlib=rb-1.2.1&w=1000&q=80',
8, 7, 'Cancel', '01-02-2019', false);
Patient patientFour = Patient('Person D', 'https://upload.wikimedia.org/wikipedia/commons/e/ec/Woman_7.jpg',
8, 4, 'Pending', '20-09-2018', true);
Patient patientFive = Patient('Person E', 'https://cdn.pixabay.com/photo/2017/08/07/14/15/portrait-2604283__340.jpg',
8, 6, 'Pending', '28-04-2017', false);
I want to store those reference variables (patientOne , patientTwo ... patientFive ) into a list.
How to do that ?
final List<Patient> patients = <Patient>[];
patients.addAll([patientOne,patientTwo,patientThree,...]);
or
final List<Patient> patients = [
Patient('Person A', 'https://images.unsplash.com/photo-1545996124-0501ebae84d0?ixid=MXwxMjA3fDB8MHxzZWFyY2h8OHx8aHVtYW58ZW58MHx8MHw%3D&ixlib=rb-1.2.1&w=1000&q=80',
8, 2, 'Pending', '10-08-2015', true),
Patient('Person A', 'https://images.unsplash.com/photo-1545996124-0501ebae84d0?ixid=MXwxMjA3fDB8MHxzZWFyY2h8OHx8aHVtYW58ZW58MHx8MHw%3D&ixlib=rb-1.2.1&w=1000&q=80',
8, 2, 'Pending', '10-08-2015', true)
,...
] ;
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 two tables:
Ticket Table
id paid_with_tax
1 5
2 6
3 7
TicketAdjustment Table
id ticket_id value_with_tax
1 1 2
2 1 1
3 1 2
4 1 3
5 2 5
The query I use:
use = 0
Ticket.objects.all().annotate(
paid_amount=Sum(
F('paid_with_tax') +
Coalesce(F('ticketadjustment__value_with_tax'), 0) * use
)
)
the query would return the following:
[
{id: 1, paid_amount: 7},
{id: 1, paid_amount: 6},
{id: 1, paid_amount: 7},
{id: 1, paid_amount: 8},
{id: 2, paid_amount: 11},
{id: 3, paid_amount: 7},
]
but the above is incorrect since the Ticket Table id=1 values are duplicated by the TicketAdjustment Table values.
how can i get the query to sum the TicketAdjustment Table values and return the following:
[
{id: 1, paid_amount: 13},
{id: 2, paid_amount: 11},
{id: 3, paid_amount: 7},
]
Here the solution for your problem :
Ticket.objects.all().annotate(
paid_amount=(F('paid_with_tax') +
Sum(Coalesce(F('ticketadjustment__value_with_tax'), 0))
)
).values_list('id', 'paid_amount')
values_list select the field you want in your result.
In your primary request there is a big problem.
Sum(F('paid_with_tax') + Coalesce(F('ticketadjustment__value_with_tax'), 0) * use)
This ligne miltiply value_with_tax with zero. So give you zero. It's like :
Sum(F('paid_with_tax'))
You want the sum of value_with_tax for each ticket, this is why I move Sum on it :
Sum(Coalesce(F('ticketadjustment__value_with_tax'), 0))
And after add the value of paid_with_tax
NB : I remove your variable use, because don't know is goal.
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.
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()