Spotfire: Multiple Average Lines on Bar Chart - average

How do I add an average line for each of the columns in my bar chart in Spotfire seperately?
The image below shows a green, blue, and red column that I would like to obtain the average of individually and then plot each on the chart.

You can iterate on each serie and then sum all points from serie, divide by amout of points and then add line by addPlotLine.
var yAxis = chart.yAxis[0];
$.each(chart.series, function(i,serie){
var average = 0;
$.each(serie.data, function(j, data){
average += data.y;
});
yAxis.addPlotLine({
value: (average / serie.data.length),
color: serie.color,
width:1
});
});
Example: http://jsfiddle.net/a04x74zc/

Related

Filling Color in anychart js chart in multiple quadrant scatter chart

Im newbie in js and anychart
I have anychart chart like this
how can i fill the color based on range like risk matrix.
*Result What i want
This is my code
// create data
var data = [
{x: 2.88, value: 3.12},
{x: 1.9, value: 2.3}
];
// create a chart
var chart = anychart.scatter();
// adjust scale min/max
chart.xScale().minimum(0).maximum(5.0);
chart.yScale().minimum(0).maximum(5.0);
// divide scale by three ticks
chart.xScale().ticks().interval(1.0);
chart.yScale().ticks().interval(1.0);
// create a bubble series and set the data
var series = chart.marker(data);
// enable major grids
chart.xGrid().enabled(true).stroke('0.1 blue');
chart.yGrid().enabled(true).stroke('0.1 blue');
var yAxis = chart.xAxis();
// set the chart title
chart.title("Quadrant-like Scatter Bubble Chart");
// set the container id
chart.container("container").draw();
});```
To get a risk matrix in the result, it’s better to use the Heatmap module.
Heatmap from your screenshot is recreated in this sample here: https://playground.anychart.com/0RAcumgI/3
Did we understand your question correctly?

Charting OHLC candle with SMA 200 using mplfinance plot function

I'm using mplfinance plot function to draw OHLC candlestick chart of a symbol. OHLC data is of 2 min timeframe. Also, I'm plotting sma 20 period and sma 200 period on the same chart. Because of sma200, the number of candles which are displayed on chart is quite huge (almost two days of 2min candle)
Since moving average is calculated internally by plot function so I've to pass the two days of 2 min candle to plot function so that I could get some data points of sma200. Candlestick chart is saved as png file. Now because of around 300 candles displayed on chart (sma20 and sma200 line also displayed), candles are not very clearly displayed.
Is there a way to restrict number of candles which get displayed on chart. If I slice my dataframe to lets say 30 candle, then sma200 will not be calculated in that case due to insufficient number of candles. What I need is sma200 with complete dataset but only fixed number of candle or for a fixed duration chart get displayed like last one hour candle data only.
mpf.plot(df, type='candle', style='charles',
title=title,
ylabel='Price',
ylabel_lower='Shares \nTraded',
mav=(20,200),
savefig=file)
I would suggest that you calculate your own moving average, and plot it using mpf.make_addplot(). This will allow you to calculate a moving average based on one-minute or two-minute candles, while plotting five-minute or ten-minute candles. For example:
# calculate mav values
mav20 = twominute_df['Close'].rolling( 20).mean()
mav200 = twominute_df['Close'].rolling(200).mean()
# resample:
resample_ohlcmap = {'Open' :'first',
'High' :'max',
'Low' :'min',
'Close' :'last',
'Volume':'sum'
}
tenminute_df = twominute_df.resample('10T').agg(resample_ohlcmap)
# plot ten-minute candles with two-minute mavs:
apmavs = [ mpf.make_addplot(mav20),
mpf.make_addplot(mav200) ]
mpf.plot(tenminute_df, type='candle', style='charles',
title=title, ylabel='Price', ylabel_lower='Shares \nTraded',
addplot=apmavs, savefig=file)
References:
resampling
moving average calculation
Thanks Daniel for your help. I'm now able to plot a chart for 60 candles with sma 20 and 200.
Well I don't need resampling as my chart timeframe and moving average time frame both are same.
Please find my code snippet.
# get list of close prices from symbol_docs. symbol_docs contain 2 min OHLC.
close_list = list(map(lambda a: a['close'], symbol_docs))
# sma20 and 200 calculated using ta-lib
sma20 = sma(close_list, 20)
sma200 = sma(close_list, 200)
# call to plot_chart function
plot_chart('TCS', symbol_docs, sma20, sma200)
def plot_chart(symbol, docs, sma20, sma200):
df = pd.DataFrame(docs)
df = df.set_index(['time'])
df.rename(columns={'open': 'Open', 'close': 'Close', 'high': 'High', 'low': 'Low'},
inplace=True)
title = symbol.upper() + ' - 2min'
file = saved_chart_image_abs_path + symbol + '.png'
df['sma20'] = sma20
df['sma200'] = sma200
df_sliced = df[-60:]
apmavs = [mpf.make_addplot(df_sliced['sma20']), mpf.make_addplot(df_sliced['sma200'])]
mpf.plot(df_sliced, type='candle', style='charles',
title=title,
ylabel='Price',
ylabel_lower='Shares \nTraded',
addplot=apmavs,
savefig=file)
telegram_message_sender.send_document(file)
os.remove(file)
Below chart is sent as a document on my telegram group :)

How to render dates on x axis prior to 1900 with d3 .js scatter plot

My d3 scatter plot uses historic date data in a range from 1600 to present. I can plot my dots successfully but can't display the dates prior to 1900 I the x axis.
I am using this example to make a scatterplot in d3 but my data has historic dates prior to 1900. I have tried to implement this solution but this returns a single date repeated for each tick mark
If I try to implement d3.axisBottom(x) this returns the dates from my data, but dates prior to 1900 are not formatted correctly.
I have made a plunker with full code
Here is my relevant scale and axis code (from the plunkr):
var x = d3.scaleTime().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
var xAxis = d3.axisBottom(x).ticks(10).tickFormat(function(d){return timeFormat(d);});
var yAxis = d3.axisLeft(y).ticks(10);
var x = d3.scaleTime()
.domain(d3.extent(data, function(d) {return (d.dates);}))
.range([ 0, width ]);
svg.append("g")
.attr("transform", "translate(0," + height + ")")
//.call(xAxis, function (d){return (d);});
//.call(xAxis, function (d){return (d.dates);}); // returns just a single date for all tick marks
.call(d3.axisBottom(x)); // partially correct dates but not formatting dates prior to 1900
My scatter plot is fine and the dots are as expected. What I want to see on the x axis is the dates prior to 1900, eg 1750.
Very grateful for help.
The referenced answer is correct, you have other issues in your code. I've also updated that answer a bit to clean the code and include a generic example with an axis from 1600-2000.
The first problem is that you define your x scale:
var x = d3.scaleTime().range([0, width]);
Then pretty much immediately define your axis:
var xAxis = d3.axisBottom(x)
.tickFormat(timeFormat);
Then you define the x domain, while redefining x as well with:
var x = d3.scaleTime()
.domain(d3.extent(data, function(d) {return (d.dates);}))
.range([ 0, width ]);
If we use svg.call(xAxis), this means that the axis is using the first x scales domain, which defaults to [January 1 2000, January 2 2000], which is why every tick will have the same year if you apply the axis with only a default domain.
Your code has .call(d3.axisBottom(x) rather than .call(xAxis), which creates a new axis again, but without the formatting needed to render pre 1900 dates
Instead, determine the scale's domain first, then create the axis:
var x = d3.scaleTime()
.range([0, width])
.domain(d3.extent(data, function(d) {return (d.dates);}))
var xAxis = d3.axisBottom(x)
.tickFormat(timeFormat);
And now you can just apply the axis:
selection
.attr("transform",...)
.call(xAxis);
Here's an updated plunkr

XAxis entry count is greater than it should be in iOS Charts 3.0.1 in Swift 3

I have two BarChartDataSets. One of them is always size 3 and the other is either 2 or 3. I tested out the code in version 3.0.0 and everything was working fine. When 3.0.1 came out, it broke my chart. I have the correct number of bars always, but I have six labels instead of 5 when the second dataset is only size 2. It has nothing to do with the stringForValue Delegate function. I set the X values using int's that are associated linearly with the Bar I want represented at that index, so each bar is equally spaced when working properly, but none of them are equally spaced when I have 6 labels and 5 bars.
The one on the left shows the issue and the one on the right shows what it looks like when my BarChartDataSet is size 3. It is duplicating whatever the last value on the chart is and adding it as a 6th label on the left. In 3.0.0 the one on the left would have only had 5 labels.
I dug into their code and where they create the labels in XAxisRendererHorizontalBarChart.swift right before they call drawLabel() I callprint("xAxis entries: \(xAxis.entries.count)")which prints xAxis entries: 6to the console even though right before I call let chartData = BarChartData(dataSets: [chartDataSet1, chartDataSet2])I callprint("dataEntries1 count: \(dataEntries1.count),
dataEntries2 count: (dataEntries2.count)")which prints dataEntries1 count: 3, dataEntries2 count: 2
First, xAxis.entries and dataSet.entries are totally different.
xAxis.entries are the values that being displayed on the axis as labels, while dataSet.entries is the value displayed for the data, e.g. the dot value in line chart, or the bar value for bar chart.
for x axis, it calculate the label count by your data entries min/max value. In Chart 3.0, x axis behaves like y axis, so it calculates x axis entries like y axis, please take a look at computeAxisValues() for details.
So xAxis.entries and dataSet.entries don't have to be equal size.
If you want to set the x axis label count same as your bars count, you can call: setLabelCount(5(6), true):
open func setLabelCount(_ count: Int, force: Bool)
{
self.labelCount = count
forceLabelsEnabled = force
}
Note, don't call the labelCount setter as it's different:
/// the number of label entries the axis should have
/// max = 25,
/// min = 2,
/// default = 6,
/// be aware that this number is not fixed and can only be approximated
open var labelCount: Int
{
get
{
return _labelCount
}
set
{
_labelCount = newValue
if _labelCount > 25
{
_labelCount = 25
}
if _labelCount < 2
{
_labelCount = 2
}
forceLabelsEnabled = false
}
}

JfreeChart: Stacked Bar Chart and CategoryAxis showing dates

I have created a stacked bar chart in which I show a count on the y axis and dates on the x axis. The problem is that when I have many dates on the x axis it gets very cluttered and impossible to read. I would like to show only some of the dates, e.g one date per week. Is that possible? I am using ChartFactory.createStackedBarChart() to create the chart, and I have the data in a DefaultCategoryDataSet.
Any input is appreciated!
For a CategoryAxis, which is used the for the domain axis in a StackedBarChart, you have considerable flexility with the method setCategoryLabelPositions(). Typical usage is illustrated in the BarChartDemo1 source, shown here.
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setCategoryLabelPositions(
CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0));
Have you tried overriding the generateLabel methods in the label generator? Something like:
chart.getCategoryPlot().getRenderer().setBaseItemLabelGenerator(
new CategoryItemLabelGenerator() {
public String generateColumnLabel(CategoryDataset dataset, Integer column) {
if(column % 7 == 0)
super.generateColumnLabel(dataset, column)
else
""
}
}
);
I haven't tested the code, but it should only output a label every 7 columns. More info on the label generator is here: http://www.jfree.org/jfreechart/api/javadoc/org/jfree/chart/labels/CategoryItemLabelGenerator.html