I'm trying to detect linear trends in data, see the example plot:

The data may be horizontal or increasing/decreasing.
I've tried kmeans clustering and dbscan with reasonable results but cannot help feeling there is probably a better algorithm out there. One of the drawbacks of using clustering is that the number of clusters has to be pre-defined, and that requires prior knowledge of the data. That will not be the case in this application as it is intended to be automated and new data trends can appear at random.
Does any one have any other suggestions to try?
You can use kmeans with some fit criteria to determine the number of clusters.
Here is an example just using kmeans and a known number of clusters based on how the data is generated:
This could be extended to increase the number of clusters until some goodness-of-fit criteria is met
This would suggest
nclusters is enough to give an adequate fit, for this examplen=0.5gives 4 lines wheren=0.25gives 5.You could use
kmedoidsand a custom distance function to more heavily weight theycoordinate instead of completely ignoring thexcoordinate if the lines aren't exclusively horizontal