I'm using jqplot to draw some charts.
But I want to set first X axis to 0.
My source code is :
plot = $.jqplot(idTag, data, options);
How I have set the [options] param to set first X axis to 0 ?
This is my data
var _DATA_CHART2 = {"chart2": {
"display_labels" : 1,
"data": [
{
"period": "0",
"medicine_name": "GL",
"dosage": "100",
"test_value": "220",
"test_date": "2013/01/02",
"drugs_name": "AMP",
'of_prescribing' : '12'
},
{
"period": "2",
"medicine_name": "GL",
"dosage": "130",
"test_value": "200",
"test_date": "2013/01/06",
"drugs_name": "AMP",
'of_prescribing' : '13ca'
},
{
"period": "4",
"medicine_name": "GL",
"dosage": "100",
"test_value": "200",
"test_date": "2013/01/10",
"drugs_name": "ACP",
'of_prescribing' : '142'
}
]
}};
And axis
var categoryX = [ [1 , '3M'],[2 , '6M'],[4 , '12M'],[6 , '18M'],[8 , '24M'],[10 , '30M'],] ;
var categoryY = [[-120, ' '],[0, 'CMR'],['', ' '],
['', ' '],['', ' '],['', ' '],
['', ' '],[100, 'MMR'],['', ' '],
['', ' '],['', ' '],['', ' '],
[190, 'CCyR'],[199, 'PCyR(Ph+<=35%)'],
[206, 'Minor CyR(Ph+<=65%)'],[215, 'CHR'],
[220, ' ']
];
Use axesDefaults and seriesDefaults. So, if you wanted both x and y axes to start at 0 and you wanted all series to not show markers, you could do:
optionsObj = {axesDefaults:{min:0}, seriesDefaults:{showMarker:false}}
var line1 = [[0, 7], [9, 14], [14, -1], [19, -1], [23, 11], [25, -1]];
var plot2 = $.jqplot('chart1', [line1], {
title: 'Stuff ',
axes:{
xaxis: {min:0}
}
});
Related
I was trying to plot animated word cloud using plotly. When the output is plot (html) I can see all the word cloud in animated way (one by one using play botton). The problem is with the slider, which doesn't move at all.
The input data are 2 lists of 4 elements: the first list are 4 diferents wikipedia texts storaged in my_test = [text1, text2, text3, text4], and the second list is year = ["1952", "1962", "1967", "1972"].
The code is:
from wordcloud import WordCloud, STOPWORDS
import plotly.graph_objs as go
from plotly.offline import plot
import plotly.offline as py
py.init_notebook_mode()
def plotly_wordcloud(text):
wc = WordCloud(width = 500,
height = 300,
margin=0,
stopwords = set(STOPWORDS),
max_words = 2000,
max_font_size = 100,
min_font_size = 10)
wc.generate(text)
word_list=[]
freq_list=[]
fontsize_list=[]
position_list=[]
orientation_list=[]
color_list=[]
for (word, freq), fontsize, position, orientation, color in wc.layout_:
word_list.append(word)
freq_list.append(freq)
fontsize_list.append(fontsize)
position_list.append(position)
orientation_list.append(orientation)
color_list.append(color)
# get the positions
x=[]
y=[]
for i in position_list:
x.append(i[0])
y.append(i[1])
# get the relative occurence frequencies
new_freq_list = []
for i in freq_list:
new_freq_list.append(i*100)
new_freq_list
return x,y,word_list,freq_list,fontsize_list,color_list,new_freq_list
my_text = [text1,text2,text3,text4]
years = ["1952", "1962", "1967", "1972"]
fig_dict = {
"data": [],
"layout": {},
"layout.update": {},
"frames": []
}
sliders_dict = {
"active": 0,
"yanchor": "top",
"xanchor": "left",
"currentvalue": {
"font": {"size": 20},
"prefix": "Year:",
"visible": True,
"xanchor": "right"
},
"transition": {"duration": 300, "easing": "cubic-in-out"},
"pad": {"b": 10, "t": 50},
"len": 0.9,
"x": 0.1,
"y": 0,
"steps": []
}
fig_dict["layout"] = {"width":1000, "height":600}
fig_dict["layout"]["xaxis"] = {"showgrid":False, "showticklabels":False, "zeroline":False}
fig_dict["layout"]["yaxis"] = {"showgrid":False, "showticklabels":False, "zeroline":False}
fig_dict["layout"]["hovermode"] = "closest"
fig_dict["layout"]["title"] = "Issues by Month"
fig_dict["layout"]["sliders"] = {
"args": ["transition", {"duration": 300,
"easing": "cubic-in-out"}],
"initialValue": "1952",
"plotlycommand": "animate",
"values": years,
"visible": True
}
fig_dict["layout"]["updatemenus"] = [
{"buttons": [
{"args": [None, {"frame": {"duration": 500, "redraw": False},
"fromcurrent": True, "transition": {"duration": 300,
"easing": "quadratic-in-out"}}],
"label": "Play",
"method": "animate"
},
{
"args": [[None], {"frame": {"duration": 0, "redraw": False},
"mode": "immediate",
"transition": {"duration": 0}}],
"label": "Pause",
"method": "animate"
}
],
"direction": "left",
"pad": {"r": 10, "t": 87},
"showactive": False,
"type": "buttons",
"x": 0.1,
"xanchor": "right",
"y": 0,
"yanchor": "top"
}]
first_time = True
for texto,year in zip(my_text,years):
x,y,word_list,freq_list,fontsize_list,color_list,new_freq_list = plotly_wordcloud(str(texto))
if first_time == True:
first_time = False
data = go.Scatter(x=x,
y=x,
textfont = dict(size=new_freq_list,
color=color_list),
name=year,
mode='text',
text=word_list
)
fig_dict["data"].append(data)
fig_dict["frames"].append(go.Frame(data=[go.Scatter(
x=x,
y=y,
textfont = dict(size=new_freq_list,
color=color_list),
name=year,
mode='text',
text=word_list
)]))
slider_step = {"args": [[year],
{"frame": {"duration": 300, "redraw": False},
"mode": "immediate",
"transition": {"duration": 300}}
],
"label": year,
"method": "animate"}
sliders_dict["steps"].append(slider_step)
fig_dict["layout"]["sliders"] = [sliders_dict]
fig = go.Figure(fig_dict)
plot(fig)
I wonder if there's any way to remove opacity from bar charts built with Chartkick in combination with ChartJS? They always appear semi-transparent, no matter what I do.
This is what I've got so far:
<%=
column_chart(
[
{:data => #invoices},
{:data => #payments}
],
:id => "chart",
:stacked => true,
:colors => ["#E91E63", "#003366"],
:legend => false,
:dataset => {:borderWidth => 0}
)
%>
Thanks for any help.
For two different color with two data-set for proper data comparison Check code snippet
//START Common for all chart
var legend = {
display: true,
position: 'bottom',
labels: {
fontColor: '#000'
}
};
//END Common for all chart
//Dataset
var data1 = {
label: 'Dataset 1',
data: [4, 6, 3, 5, 2, 3],
backgroundColor: 'rgba(255, 99, 132, 1)', //Set 1 for remove transparency
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 1
};
var data2 = {
label: 'Dataset 2',
data: [5, 2, 3, 4, 6, 3],
backgroundColor: 'rgba(54, 162, 235, 1)', //Set 1 for remove transparency
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
};
var Dataset = [data1, data2]
// Dataset
//START Bar chart
var option = {
scales: {
yAxes: [{
gridLines: {
offsetGridLines: true
},
categorySpacing: 5,
ticks: {
beginAtZero: true
}
}]
},
responsive: true,
//maintainAspectRatio: false,
legend: legend,
//onClick: LoadDataInDetails
}
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: Dataset
},
options: option
});
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<canvas id="myChart"></canvas>
OK, it seems that only RGB colours can be passed into column_chart() (correct me if I'm wrong). This is what I ended up with:
<%=
column_chart(
[
{:data => #invoices},
{:data => #payments}
],
:id => "chart",
:stacked => true,
:colors => [to_rgba("#E91E63"), to_rgba("#003366")],
:legend => false,
:dataset => {:borderWidth => 0}
)
%>
module ColorHelper
def to_rgba(hex_value)
opacity = 1
hex_value = hex_value.gsub('#', '')
rgb_values = hex_value.scan(/../).map{ |x| x.hex }
rgb_values << opacity
"rgba(#{rgb_values.join(',')})"
end
end
Not perfect, but it gets the job done.
I want to use export excel and print the datatable .I use following code but not able to use both options for selected columns.
$('#example').DataTable( {
dom: 'Blfrtip',
buttons: [
{
extend: 'excel','print',
exportOptions: {
columns: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
},
}
],
"lengthMenu": [[200, 250, 500, -1], [200, 250, 500, "All"]],
"bLengthChange" : true,
initComplete: function () {
this.api().columns().every( function () {
var column = this;
var select = $('<select><option value="">Select</option></select>')
.appendTo( $(column.footer()).empty() )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
} );
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
} );
}
} );
I am not figure out what happens wrong.Please help me.
{
extend: 'excel'
exportOptions: {
columns: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
},
{
extend: 'print'
exportOptions: {
columns: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
}
One of the most commonly used is the columns option which defines the columns that should be used as part of the export. This is given as a column-selector, making it simple to tell it if you want only visible columns, or a mix of the columns available.
and this is a simple of how it can be done :
function attachDataTable(tableId: string) {
let companyFunctionTable = $('#' + tableId).DataTable({
dom: 'Bfrtip',
buttons: [
//'csvHtml5'
{
extend: 'csvHtml5',
exportOptions: {
columns: [0, 1, 2]
},
className: 'btn btn-sm btn-outline-secondary',
text: `<i class="fa fa-file-csv"></i> ${i18next.t('Export to CSV')}`, titleAttr: i18next.t('Export to CSV'),
bom: true
},
],
"initComplete": function (settings, json) {
placeToolbarButton(tableId);
},
"paging": globalVar.dataTablesSettings.paging,
"stateSave": false,
"stateSaveParams": function (settings, data: any) {
data.search.search = "";
},
"order": [],
"lengthChange": false,
"pageLength": globalVar.dataTablesSettings.pageLength,
"language": {
"url": globalVar.dataTablesSettings.languageUrl
}
});
}
Please fellow that link :
https://datatables.net/extensions/buttons/examples/html5/columns.html
Don't forget to include the required JS libraries needed to display the exporting functionality.
Just modify your buttons option this way
buttons: [
{
extend: 'excel',
exportOptions: {
columns: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
},
},
{
extend: 'print',
exportOptions: {
columns: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
},
},
]
elaborated #tdymicroit answer
I have data of the following format:
[
{"ID": 1, "title": Temporary Title, "team": TeamA, "group": 1},
{"ID": 2, "title": One Dinosaur, "team": TeamA, "group": 2},
{"ID": 3, "title": Another Book, "team": TeamB, "group": 1},
{"ID": 4, "title": Try Again, "team": TeamC, "group": 1},
{"ID": 5, "title": Last One, "team": TeamC, "group": 2}
]
I want a pie chart that shows the distribution of items in group 1 by team, and a datatable (grid) that shows me all entries in group 2. A team filter should be able to apply to both the charts.
I am pretty confused on how to handle the grouping/filtering to achieve this. Here is what I have right now, but it automatically filters everything down to group 2.
var byTeamForPie = data.dimension(function (s) {
return s.team;
});
var group1Counts = byTeamForPie.group().reduceCount(function (d) {
if (d.group == 1) {
return 1;
}
return 0;
});
var pieChart = dc.pieChart("#teamPieChart");
pieChart
.width(500)
.height(580)
.innerRadius(10)
.dimension(byTeam)
.group(group1Counts);
var byGroup = data.dimension(function (s) {
return s.group;
});
byGroup.filter(2);
datatable = $('#chart').DataTable({
"info": true,
"responsive": true,
"pagingType": "full_numbers",
"lengthChange": true,
"pageLength": 15,
"lengthMenu": [10, 25, 50],
"bLengthChange": false,
"bFilter": false,
"bSort": true,
"bInfo": false,
"bAutoWidth": false,
"bDeferRender": true,
"aaData": byGroup.top(Infinity),
"bDestroy": true,
"aoColumns": [
{ "mData": "ID", "sDefaultContent": "" },
{ "mData": "title", "sDefaultContent": " " },
{ "mData": "team", "sDefaultContent": " " },
{ "mData": "group", "sDefaultContent": " " }
]
});
var byTeam = data.dimension(function (s) { return s.team; });
var teams = byTeam.group();
var filtered_teams = remove_empty_bins(teams);
var teamsChart = dc.rowChart("#teamChart");
teamsChart.width(300).height(300).dimension(byTeam).group(filtered_teams).label(function (d) {
return d.key;
})
.labelOffsetX(-50)
.ordering(function (d) {
return -d.value;
})
.title(function (d) {
return d.value;
})
.elasticX(true).x(d3.scale.ordinal())
.margins({ top: 10, bottom: 30, left: 55, right: 10 });
Note: I haven't included the refreshtable() function for the datatable here
Not sure if this is ideal, but I'd say remove the byGroup.filter(2); and change
"aaData": byGroup.top(Infinity)
to
"aaData": byGroup.top(Infinity).filter(function(d) { return d.group === 2; })
In Crossfilter, filters applied to dimensions are applied to all other dimensions and groups. So when you do byGroup.filter(2), your group1Counts will all go to 0.
You might want to consider using dc.js's data table widget instead, as that will automatically update without you having to manage it.
I want to create a bar chart with time duration on the bottom axis. It' working for decimal numbers, like 300.5 seconds, or 50.3 hours, but i would like to have the following format:
Hours:Minutes:Seconds. I tried some thing with datalabelformat: datetime, but with no success.
The data would be for example:
Member1 - 10:05:18
Member2 - 12:52:20
Member3 - 18:10:30
Member4 - 19:20:10
Member5 - 19:30:45
Anybody got an idea how to realize that?
Thanks in advance!
You need to set min value and tickInterval, then set dateTimeLabels.
dateTimeLabelFormats: {
millisecond: '%H:%M:%S',
second: '%H:%M:%S',
minute: '%H:%M:%S',
hour: '%H:%M:%S',
day: '%H:%M:%S',
week: '%H:%M:%S',
month: '%H:%M:%S',
year: '%H:%M:%S'
}
Example:
http://jsfiddle.net/TynTT/1/
I came here searching for a solution to my problem. Not sure if this is exactly what you want, and I cannot put in a comment due to low reputation. But this is how I was able to solve it.
This provides result in hh:mm. You can modify it to include seconds.
http://jsfiddle.net/TynTT/11/
It has the y axis in hh:mm format and also displays datalabels as hh:mm.
$(function () {
$('#container').highcharts({
chart: {
type: 'column'
},
yAxis: {
type: 'time',
labels: {
formatter: function () {
var time = this.value;
var hours1=parseInt(time/3600000);
var mins1=parseInt((parseInt(time%3600000))/60000);
return (hours1 < 10 ? '0' + hours1 : hours1) + ':' + (mins1 < 10 ? '0' + mins1 : mins1);
}
}
},
series: [{
data: [1000000, 26500000, 17000050, 79000000, 56000000, 124000000],
dataLabels: {
enabled: true,
formatter: function () {
var time = this.y / 1000;
var hours1=parseInt(time/3600);
var mins1=parseInt((parseInt(time%3600))/60);
return (hours1 < 10 ? '0' + hours1 : hours1) + ':' + (mins1 < 10 ? '0' + mins1 : mins1);
}
},
}]
});
});
I improved above configs by reusing the HC methods:
durationbar: {
chart: {
type: 'column'
},
yAxis: {
type: 'datetime',
showFirstLabel: false,
dateTimeLabelFormats: {
millisecond: '%H:%M:%S'
},
units: [[
'millisecond',
[1000]
], [
'second',
[1, 2, 5, 10, 15, 30]
], [
'minute',
[1, 2, 5, 10, 15, 30]
], [
'hour',
[1, 2, 3, 4, 6, 8, 12]
], [
'day',
[1]
], [
'week',
[1]
], [
'month',
[1, 3, 6]
], [
'year',
null
]],
},
tooltip: {
formatter: null,
pointFormat: '{point.name}: <b>{point.dataLabel.text.textStr}</b><br/>'
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
formatter() {
return this.series.chart.time.dateFormat('%H:%M:%S', this.y)
}
}
}
}
},
screenshot